简体   繁体   中英

Create and use Babel plugin without making it a npm module

In my project, I'm using Babel 6 with the require hook. I need to load a custom babel plugin that I wrote. But do I really need to publish my plugin using npm first, and then include the plugin name in my main project's .babelrc ?

Is there any way to just directly load the plugin code? In other words, can I just load the following directly?

export default function({types: t }) {
  return {
    visitor: {
      ...
    }
  };
}

Where you list your plugins in your .babelrc, provide the path to your plugin instead of your standard published plugin name.

"plugins": ["transform-react-jsx", "./your/plugin/location"]

When exporting your plugin function, you'll probably need to use module.exports = instead of export default , since ES2015 modules haven't been fully implemented in Node yet.

This is my entire babel.config.js file.

module.exports = function (api) {
  api.cache(true);

  const presets = ["@babel/preset-env", "@babel/preset-react"];
  const plugins = [ 
    ["@babel/plugin-proposal-pipeline-operator", { "proposal": "minimal" }],
    "c:\\projects\\my-babel-plugin"
  ];

  return {
    presets,
    plugins
  };
}

First item in the plugins array is a plugin with options in form of an array. Second item is my own local plugin.

Inside of my-babel-plugin folder there needs to be a package.json with the "main" entry, usually "main": "lib/index.js" or "main": "src/index.js" .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM