# Plugins

Creating plugins in GrapesJS is pretty straightforward and here you'll get how to achieve it.

WARNING

This guide is referring to GrapesJS v0.21.2 or higher

# Basic plugin

Plugins are simple functions that are run when the editor is initialized.

function myPlugin(editor) {
  // Use the API: https://grapesjs.com/docs/api/
  editor.Blocks.add('my-first-block', {
    label: 'Simple block',
    content: '<div class="my-block">This is a simple block</div>',
  });
}

const editor = grapesjs.init({
  container: '#gjs',
  plugins: [myPlugin]
});

This means plugins can be moved to separate folders to keep thing cleaner or imported from NPM.

import myPlugin from './plugins/myPlugin'
import npmPackage from '@npm/package'

const editor = grapesjs.init({
    container : '#gjs',
    plugins: [myPlugin, npmPackage]
});

# Plugins with options

It's also possible to pass custom parameters to plugins in to make them more flexible.

const myPluginWithOptions = (editor, options) => {
  console.log(options);
  // { customField: 'customValue' }
}

const editor = grapesjs.init({
  container : '#gjs',
  plugins: [myPluginWithOptions],
  pluginsOpts: {
    [myPluginWithOptions]: {
      customField: 'customValue'
    }
  }
});

# Usage with TS

If you're using TypeScript, for a better type safety, we recommend using the usePlugin helper.

import grapesjs, { usePlugin } from 'grapesjs';
import type { Plugin } from 'grapesjs';

interface MyPluginOptions {
  opt1: string,
  opt2?: number,
}

const myPlugin: Plugin<MyPluginOptions> = (editor, options) => {
    // ...
}

grapesjs.init({
  // ...
  plugins: [
    // no need for `pluginsOpts`
    usePlugin(myPlugin, { opt1: 'A', opt2: 1 })
  ]
});

# Boilerplate

For fast plugin development, we highly recommend using grapesjs-cli (opens new window) which helps to avoid the hassle of setting up all the dependencies and configurations for development and building (no need to touch Webpack or Babel configurations). For more information check the repository.