• Plugin Options" level="1">Plugin Options
    • Pre and Post in Plugins" level="2"> Pre and Post in Plugins
    • Enabling Syntax in Plugins" level="2"> Enabling Syntax in Plugins
    • Throwing a Syntax Error" level="2"> Throwing a Syntax Error

    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:

    1. {
    2. plugins: [
    3. ["my-plugin", {
    4. "option1": true,
    5. "option2": false
    6. }]
    7. ]
    8. }

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

    1. export default function({ types: t }) {
    2. return {
    3. visitor: {
    4. FunctionDeclaration(path, state) {
    5. console.log(state.opts);
    6. // { option1: true, option2: false }
    7. }
    8. }
    9. }
    10. }

    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.

    1. export default function({ types: t }) {
    2. return {
    3. pre(state) {
    4. this.cache = new Map();
    5. },
    6. visitor: {
    7. StringLiteral(path) {
    8. this.cache.set(path.node.value, 1);
    9. }
    10. },
    11. post(state) {
    12. console.log(this.cache);
    13. }
    14. };
    15. }

    Enabling Syntax in Plugins" class="reference-link"> Enabling Syntax in Plugins

    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.

    1. export default function({ types: t }) {
    2. return {
    3. inherits: require("babel-plugin-syntax-jsx")
    4. };
    5. }

    Throwing a Syntax Error" class="reference-link"> Throwing a Syntax Error

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

    1. export default function({ types: t }) {
    2. return {
    3. visitor: {
    4. StringLiteral(path) {
    5. throw path.buildCodeFrameError("Error message here");
    6. }
    7. }
    8. };
    9. }

    The error looks like:

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