如何正确使用ES6“export default”与CommonJS“需要” [英] How to correctly use ES6 "export default" with CommonJS "require"?
问题描述
我一直在使用 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按钮从'./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).
我通过在需要调用之后追加 .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?
推荐答案
p>要与Babel一起使用 export default
,您可以执行以下操作之一:
To use export default
with Babel, you can do 1 of the following:
-
require(myStuff)。default
-
npm install babel-plugin-add-module-出口--save-dev
require("myStuff").default
npm install babel-plugin-add-module-exports --save-dev
或3:
//myStuff.js
var thingToExport = {};
Object.defineProperty(exports, "__esModule", {
value: true
});
exports["default"] = thingToExport;
这篇关于如何正确使用ES6“export default”与CommonJS“需要”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!