我应该如何使用 browserify 和 babelify 转换 ES6 node_modules? [英] How should I transform ES6 node_modules with browserify and babelify?

查看:20
本文介绍了我应该如何使用 browserify 和 babelify 转换 ES6 node_modules?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 gulp、browserify 和 babelify 以便在我的项目中使用 ES6 语法.一旦我导入了一个也是用 ES6 编写的 node_module,gulp 就会抛出一个错误:'import' and 'export' may appear only with 'sourceType: module'

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'

我已经阅读了 babelify 的 github 上提出的解决方案页.简而言之,有两种可能:

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

  1. 在受影响的 node_module 的 package.json 中添加 browserify 选项
  2. 配置 gulp,以便 browserify 尝试使用 babelify 转换所有文件(并为不必要的文件添加忽略选项).

第一个选项会阻止其他人克隆我的项目并立即启动并运行它.是否有解决方法,可能使用 npm 后安装脚本?

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 有一个 only 选项,可用于避免转译不匹配的文件一个正则表达式.当与 Browserify 的 global 选项结合使用时(默认情况下,转换不会应用于 node_modules 目录中的文件),您可以选择性地转译 node_modules 中的文件.

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.

使用此示例配置:

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

不在 node_modules 中的文件将不会被编译,除非它们位于以下之一中:

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

  • /node_modules/a
  • /node_modules/b

如果node_modules下只有一个目录需要转译,可以将正则表达式简化为:

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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆