Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How should I transform ES6 node_modules with browserify and babelify?

I'm using gulp, browserify and babelify in order to use ES6 syntax in my project. As soon as I import a node_module, which was also written in ES6, gulp throws an error: 'import' and 'export' may appear only with 'sourceType: module'

I've read the proposed solutions on babelify's github page. In short, the two possibilities are:

  1. Add a browserify option to the affected node_module's package.json
  2. Configure gulp, so that browserify tries to transform all files with babelify (and add an ignore-option for unnecessary files).

The first option would prevent others from being able to clone my project and get it up and running right away. Is there a workaround, perhaps using an npm postinstall script?

The second option seems like an overkill. Is there a more elegant solution for this?

like image 790
pwagner Avatar asked Sep 04 '16 20:09

pwagner


1 Answers

Babelify has an only option that can be used to avoid transpiling files that don't match a regular expression. When combined with Browserify's global option (by default, transforms are not applied to files within the node_modules directory), you can selectively transpile files within node_modules.

With this example configuration:

browserify({ entries: ["index.js"] })
  .transform("babelify", {
    global: true,
    only: /^(?:.*\/node_modules\/(?:a|b)\/|(?!.*\/node_modules\/)).*$/,
    presets: ["es2015"]
  })
  .bundle()
  .pipe(fs.createWriteStream("bundle.js"));

files not within node_modules will not be compiled unless they are in one of:

  • /node_modules/a
  • /node_modules/b

If you have only one directory under node_modules that you want transpiled, you can simplify the regular expression to:

/^(?:.*\/node_modules\/a\/|(?!.*\/node_modules\/)).*$/

and if you have more, you can add them:

/^(?:.*\/node_modules\/(?:a|b|c|d)\/|(?!.*\/node_modules\/)).*$/
like image 81
cartant Avatar answered Oct 15 '22 01:10

cartant