如何正确使用ES6“导出默认值"使用 CommonJS“需要"? [英] How to correctly use ES6 "export default" with CommonJS "require"?

查看:25
本文介绍了如何正确使用ES6“导出默认值"使用 CommonJS“需要"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在学习 Webpack 教程.在其中一节中,它给出了包含该问题一行本质的代码示例:

I've been working through Webpack tutorial. In one of the sections, it gives the code example that contains one line of essence to this question:

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

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

In the next section of said tutorial, titled "Code splitting", the class defined above is loaded on demand, like this:

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

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

Unfortunately, this code throws an exception:

Uncaught TypeError: Button is not a function

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

Now, I know that the right way to include ES6 module would be to simply import Button from './Components/Button'; at the top of the file, but using a construct like that anywhere else in the file makes babel a sad panda:

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

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

After some fiddling with previous (require.ensure()) example above, I realized that ES6 export default syntax exports an object that has property named default, which contains my code (the Button function).

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

I did fix the broken code example by appending .default after require call, like this:

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

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

...but I think it looks a bit clumsy and it is error-prone (I'd have to know which module uses ES6 syntax, and which uses good old module.exports).

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

Which brings me to my question: what is the right way to import ES6 code from code that uses CommonJS syntax?

推荐答案

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

To use export default with Babel, you can do 1 of the following:

  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;

这篇关于如何正确使用ES6“导出默认值"使用 CommonJS“需要"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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