Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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: {
      ...
    }
  };
}
like image 510
Dave Avatar asked Apr 02 '16 03:04

Dave


2 Answers

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.

like image 64
Justin Silvestre Avatar answered Sep 19 '22 17:09

Justin Silvestre


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".

like image 22
Ska Avatar answered Sep 17 '22 17:09

Ska