问题描述
app.js
export default function(){}
index.js
require('babel / register');
require('./ app')();
然后,我可以运行 node index.js
没有错误。但是,使用Babel 6.x,运行以下代码
index.es6.js
require('babel-core / register');
require('./ app')();
导致错误
我想知道为什么?
TL; DR
p>
require('./ app')。
说明
Babel 5曾经有 export default
的兼容性黑客:如果一个模块只包含一个导出,并且它是默认导出,则它被分配给 module.exports
。因此,例如,您的模块 app.js
export default function(){}
将被转载到这个
使用严格;
Object.defineProperty(exports,__esModule,{
value:true
});
exports [default] = function(){};
module.exports = exports [default];
纯粹完成以兼容 require Babel-transpiled模块(就像你在做)。也是不一致的如果一个模块包含命名和默认导出,它不能是
require
-d。
在现实中,对于ES6模块规范,与名称为 default
的命名导出相比,默认导出为不同。它只是语法糖,可以在编译时静态解决,所以这个
从'./app'导入一些东西。
与此相同
<$ p $从./app中导入{default}作为某个东西} p>
就是说,看来Babel 6决定放弃模块的互操作性。现在,您的模块 app.js 被转载为 'use strict';
Object.defineProperty(exports,__esModule,{
value:true
});
exports.default = function(){};
如你所见,没有更多的赋值给 module.exports
。要需要
这个模块,你需要做
require('。 /应用)的默认();
In Babel 5.x, I can write the following code:
app.js
export default function (){}
index.js
require('babel/register');
require('./app')();
Then, I can run node index.js
with no errors. However, using Babel 6.x, running the following code
index.es6.js
require('babel-core/register');
require('./app')();
results in an error
I want to know why?
解决方案 TL;DR
You have to use
require('./app').default();
Explanation
Babel 5 used to have a compatibility hack for export default
: if a module contained only one export, and it was a default export, it was assigned to module.exports
. So, for example, your module app.js
export default function () {}
would be transpiled to this
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports["default"] = function () {};
module.exports = exports["default"];
This was done purely for compatibility with require
-ing Babel-transpiled modules (like you are doing). It was also inconsistent; if a module contained both named and default exports, it could not be require
-d.
In reality, according to the ES6 module spec, a default export is no different than a named export with the name default
. It is just syntactic sugar which can be statically resolved at compile time, so this
import something from './app';
is the same as this
import { default as something } from './app';
That being said, it appears that Babel 6 decided to drop the interoperability hack when transpiling modules. Now, your module app.js is transpiled as
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = function () {};
As you see, no more assignment to module.exports
. To require
this module, you need to do
require('./app').default();
这篇关于在Babel 6.x中无法require()默认导出值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!