---
sidebar_position: 2
---

# Plugin Object

The Module Tools plugin is an object, and the object contains the following properties.

- `name`: The name of the plugin, a unique identifier.
- `setup`: plugin initialization function, which will be executed only once. setup function can return a [Hooks object](), and Module Tools will execute the function corresponding to the Hook defined on the Hooks object at a specific time.

For example, in the following plugin code example, the `beforeBuild` function is triggered before the project starts the build task and the `build start` log is printed.

<CH.Code>

```ts . /plugins/demo.tsx
import type { CliPlugin, ModuleTools } from '@modern-js/module-tools';

const myPlugin: CliPlugin<ModuleTools> = {
  name: 'my-plugin',

  setup() {
    return {
      // this is hook
      beforeBuild: () => {
        console.info('build start');
      },
    };
  },
};
```

---

```ts . /modern.config.ts
import { myPlugin } from '. /plugins/demo';
export default {
  plugins: [myPlugin()],
};
```

</CH.Code>

## Plugin type definitions

When using TypeScript, you can introduce the built-in `CliPlugin` and `ModuleTools` types to provide the correct type derivation for plugins: ``

```ts
import type { CliPlugin, ModuleTools } from '@modern-js/module-tools';

const myPlugin: CliPlugin<ModuleTools> = {
  name: 'my-plugin',

  setup() {
    const foo = '1';

    return {
      // this is hook
      afterBuild: () => {
        //...
      },
    };
  },
};
```

## Plugin configuration items

**It is recommended to write the plugin as a function**, so that the plugin can receive configuration items via function entry.

```ts
import type { CliPlugin, ModuleTools } from '@modern-js/module-tools';

type MyPluginOptions = {
  foo: string;
};

const myPlugin = (options: MyPluginOptions): CliPlugin<ModuleTools> => ({
  name: 'my-plugin',

  setup() {
    console.log(options.foo);
  },
});
```
