Babel ES6模块:为什么babel重命名进口

时间:2015-12-09 10:49:35

标签: ecmascript-6 babeljs

在我的ES6导入器上运行babel时,它会一直重命名我的导入源:

import {foo as bar} from './bar';
console.log(bar);

变为

'use strict';
var _bar = require('./bar');
console.log(_bar.foo);

命名导入重命名为:

import {bar} from './bar';
console.log(bar);

'use strict';
var _bar = require('./bar');
console.log(_bar.bar);

默认导入更糟糕,因为还添加了2:

import bar from './bar';
console.log(bar);

变为

'use strict';
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _bar = require('./bar');
var _bar2 = _interopRequireDefault(_bar);
console.log(_bar2['default']);

为什么babel会这样做?背景:在Chrome中调试应用程序时,我需要转到源文件以了解如何重命名变量以获取其当前值,因为Chrome不知道bar已重命名为_bar.bar它...使用像WebStorm这样的工具几乎不可能进行调试......

为什么不能将命名导入转换为

'use strict';
var _bar = require('./bar');
var bar = _bar.bar;
console.log(bar);

并默认导入

'use strict';
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _bar = require('./bar');
var _bar2 = _interopRequireDefault(_bar);
var bar = _bar2['default']
console.log(bar);

1 个答案:

答案 0 :(得分:5)

That is done to simulate "reference" nature of module imports. In

import {foo as bar} from './bar';
console.log(bar);

bar is not just a variable that holds a value, it's a reference to the export from the other module. If the exported values changes, so will the import.

Example:

// a.js
export var a = 42;
setTimeout(() => a = 21, 500);

// b.js
import {a} from './a';
setTimeout(() => console.log(a), 1000);

According to the spec, the code in b.js has to log 21. Since JavaScript doesn't have assign-by-reference, the only way to achieve such a behavior is to convert every import to a MemberExpression (foo.bar).