Plugin Options

Plugin Options" class="reference-link">Plugin Options

If you would like to let your users customize the behavior of your Babel plugin you can accept plugin specific options which users can specify like this:

{  plugins: [    ["my-plugin", {      "option1": true,      "option2": false    }]  ]}

These options then get passed into plugin visitors through the state object:

export default function({ types: t }) {  return {    visitor: {      FunctionDeclaration(path, state) {        console.log(state.opts);        // { option1: true, option2: false }      }    }  }}

These options are plugin-specific and you cannot access options from other plugins.

Pre and Post in Plugins" class="reference-link"> Pre and Post in Plugins

Plugins can have functions that are run before or after plugins. They can be used for setup or cleanup/analysis purposes.

export default function({ types: t }) {  return {    pre(state) {      this.cache = new Map();    },    visitor: {      StringLiteral(path) {        this.cache.set(path.node.value, 1);      }    },    post(state) {      console.log(this.cache);    }  };}

Babel plugins themselves can enable parser plugins so that users don’t need to install/enable them. This prevents a parsing error without inheriting the syntax plugin.

export default function({ types: t }) {  return {    inherits: require("babel-plugin-syntax-jsx")  };}

If you want to throw an error with babel-code-frame and a message:

export default function({ types: t }) {  return {    visitor: {      StringLiteral(path) {        throw path.buildCodeFrameError("Error message here");      }    }  };}

The error looks like:

file.js: Error message here   7 |   8 | let tips = [>  9 |   "Click on any AST node with a '+' to expand it",     |   ^  10 |  11 |   "Hovering over a node highlights the \  12 |    corresponding part in the source code",