How should I transform ES6 node_modules with browserify and babelify?

孤人 提交于 2019-12-10 14:16:16

问题


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?


回答1:


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\/)).*$/


来源:https://stackoverflow.com/questions/39321384/how-should-i-transform-es6-node-modules-with-browserify-and-babelify

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!