Browserify 独立选项不直接包装具有指定名称的代码?

Browserify standalone option doesn't directly wraps the code with specified name?

我尝试使用gulp、browserify、watchify和babelify来编译一个独立的js模块。 选项是这样的:

const browserifyOpts = {
  debug: true,
  entries: path.join('src', 'index.js'),
  standalone: 'Goo',
  transform: [
    'babelify',
  ],
};

我的JS模块如下:

export default class Goo {
  constructor() {
    this.a = 'hello';
  }
}

编译正常。但是当我把它包含在html文件中的脚本标签中时,Goo模块被包裹在window.Goo.default里面,也就是说,我不能直接使用:

new Goo();

但必须使用:

new Goo.default();

知道哪里出了问题吗? 谢谢!

默认情况下,Babel 6 以不同方式处理默认模块导出。如果您想使用旧版本,可以使用 add-module-exports 插件。

要么将其添加到您的 .babelrc 中,要么将其添加为 Babelify 中的一个选项。

来自此 Github Issue 的更多信息:

has to do with the new way Babel handles default exports. if you dont want to have to reference the default key, you need to use this plugin: https://github.com/59naga/babel-plugin-add-module-exports

最简单的选择是通过让 index.js 文件包含类似

的内容来自己包装它
module.exports = require('./main').default;

并将您当前的 index.js 移动到 main.js。那你就准备好了。

正如其他答案所说,您可以使用 babel-plugin-add-module-exports,但这不是我通常推荐的方法,因为虽然它解决了这个问题,但它也引入了您可能会不小心编写 import/export 对有效但不符合规范。