【问题标题】:How to correctly use ES6 "export default" with CommonJS "require"?如何正确使用 ES6“导出默认值”和 CommonJS“要求”?
【发布时间】:2016-06-28 12:25:22
【问题描述】:

我一直在处理Webpack tutorial。在其中一节中,它给出了包含该问题的一行本质的代码示例:

export default class Button { /* class code here */ }

在该教程的下一部分,标题为“代码拆分”,上面定义的类是按需加载的,如下所示:

require.ensure([], () => {
    const Button = require("./Components/Button");
    const button = new Button("google.com");
    // ...
});

不幸的是,这段代码抛出了异常:

Uncaught TypeError: Button is not a function

现在,我知道包含 ES6 模块的 正确 方法是在文件顶部简单地 import Button from './Components/Button';,但是在文件中的其他任何地方使用类似的构造会使 babel 成为悲伤的熊猫:

SyntaxError: index.js: 'import' and 'export' may only appear at the top level

在对上面的 (require.ensure()) 示例进行了一番摆弄之后,我意识到 ES6 export default 语法导出了一个具有名为 default 的属性的对象,其中包含我的代码(Button 函数)。

我确实通过在 require 调用后附加 .default 来修复损坏的代码示例,如下所示:

const Button = require("./Components/Button").default;

...但我认为它看起来有点笨拙,而且容易出错(我必须知道哪个模块使用 ES6 语法,哪个使用旧的 module.exports)。

这让我想到了我的问题:从使用 CommonJS 语法的代码中导入 ES6 代码的正确方法是什么?

【问题讨论】:

    标签: javascript ecmascript-6 webpack commonjs es6-module-loader


    【解决方案1】:

    要将export default 与 Babel 一起使用,您可以执行以下操作之一:

    1. require("myStuff").default
    2. npm install babel-plugin-add-module-exports --save-dev

    或 3:

    //myStuff.js
    var thingToExport = {};
    Object.defineProperty(exports, "__esModule", {
      value: true
    });
    exports["default"] = thingToExport;
    

    【讨论】:

    • 找出所有细节的最快方法是使用babel-cli 转译一个文件并查看结果。只需要defineProperty-thing... - 所以感谢您指出所有这些
    【解决方案2】:

    如果有人使用 gulp + browserify + babelify 在客户端捆绑 js 使用。

    试试下面的代码[gulpfile.js]

    browserify({
      entries: "./ui/qiyun-ui/javascripts/qiyun-ui.src.js",
      standalone: "qyUI" // To UMD
    })
    .transform(babelify, {
      presets: ["env"],
      plugins: ["add-module-exports"] // export default {} => module.exports = exports['default'];
    })
    .bundle()
    

    别忘了安装这个包: https://www.npmjs.com/package/babel-plugin-add-module-exports

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-05-24
      • 2019-12-18
      • 2016-08-02
      • 2020-10-14
      • 2020-05-22
      • 1970-01-01
      • 2017-12-02
      • 1970-01-01
      相关资源
      最近更新 更多