---
sidebar_position: 2
---

# Plugin Object

The Modern.js Module 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 Modern.js Module 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.

```ts title=". /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 title="modern.config.ts"
import { myPlugin } from '. /plugins/demo';
export default {
  plugins: [myPlugin()],
};
```

## 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 options

**It is recommended to write the plugin as a function**, so that the plugin can receive configuration options 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);
  },
});
```
