如何正确使用 ES6 “导出默认” 和 CommonJS “require”

How to correctly use ES6 "export default" with CommonJS "require"?

本文关键字:导出默认 require CommonJS 默认 何正确 ES6      更新时间:2023-09-26

我一直在学习Webpack教程。在其中一个部分中,它给出了代码示例,其中包含此问题的一行本质:

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 函数)。

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

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

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

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

要将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;

如果有人使用 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