问题描述
为了在我的项目中使用ES6语法,我使用了gulp,browserify和babelify。只要我导入一个也写在ES6中的node_module,gulp会抛出一个错误:'import'和'export'可能只与'sourceType:module'一起出现
我已阅读。简而言之,这两种可能性是:
- 为受影响的node_module的package.json添加一个browserify选项
- 配置gulp,以便browserify尝试使用babelify转换所有文件(并为不必要的文件添加忽略选项)。
- 配置gulp,以便browserify尝试使用babelify转换所有文件(并为不必要的文件添加忽略选项)。
第一个选项会阻止其他人克隆我的项目并立即启动并运行。是否有解决方法,可能使用npm postinstall脚本?
第二个选项看起来像是一种矫枉过正。有没有一个更优雅的解决方案呢?
只有选项,可用于避免转译与正则表达式不匹配的文件。当与Browserify的 global
选项结合使用时(默认情况下,转换不适用于 node_modules
目录中的文件),您可以有选择地在 node_modules
中传输文件。
使用以下配置示例:
browserify({entries:[index.js]})
.transform(babelify,{
global:true,
only:/^(?:.*\/node_modules\/(?:a|b)\/?(?!.*\/node_modules\/)).*$/,
预设:[es2015]
})
.bundle()
.pipe(fs.createWriteStream(bundle.js));
文件不在 node_modules
内不会被编译除非它们在以下之一中:
/ node_modules / a
/ node_modules / b
只需要在 node_modules
下的一个目录进行转换,就可以将正则表达式简化为:
/ ^(?:。* \ / node_modules \ / a \ / |(!!。* \ / node_modules \ / /)).*$/
$ c
$ p
$ b 如果你有更多,你可以添加它们:
/ ^(?:?!。* \ / node_modules\ /(?:A | b | C | d)\ / |(* \ / node_modules\ /))。 * $ /
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:
- Add a browserify option to the affected node_module's package.json
- 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?
解决方案 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\/)).*$/
这篇关于我应该如何用browserify和babelify转换ES6 node_modules?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!