pwagner pwagner - 1 year ago 143
Node.js Question

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?

Answer Source

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

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:


and if you have more, you can add them:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download