在 Babel 6.x 中不能 require() 默认导出值 [英] Can't require() default export value in Babel 6.x

查看:13
本文介绍了在 Babel 6.x 中不能 require() 默认导出值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Babel 5.x 中,我可以编写如下代码:

In Babel 5.x, I can write the following code:

app.js

export default function (){}

index.js

require('babel/register');
require('./app')();

然后,我可以毫无错误地运行 node index.js.但是,使用 Babel 6.x,运行以下代码

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')();

导致错误

require(...) 不是函数

require(...) is not a function

我想知道为什么?

推荐答案

TL;DR

你必须使用

const app = require('./app').default;
app();

说明

Babel 5 曾经对 export default 有一个兼容性黑客:如果一个模块只包含一个导出,并且它是一个默认导出,它被分配给 module.exports.因此,例如,您的模块 app.js

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 () {}

会转译成这个

"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});

exports["default"] = function () {};

module.exports = exports["default"];

这样做纯粹是为了与 require-ing Babel-transpiled 模块兼容(就像你在做的那样).它也不一致;如果一个模块同时包含命名导出和默认导出,则它不能是 require-d.

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.

实际上,根据 ES6 模块规范,默认导出与名称为 default 的命名导出没有什么不同.它只是可以在编译时静态解析的语法糖,所以这个

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';

和这个一样

import { default as something } from './app';

话虽如此,看来 Babel 6 决定在转译模块时放弃互操作性黑客.现在,您的模块 app.js 被转译为

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 () {};

如您所见,不再分配给 module.exports.要require这个模块,你需要做

As you see, no more assignment to module.exports. To require this module, you need to do

const app = require('./app').default;
app();

或者,更简洁,更接近您的原始代码:

Or, more concisely, and closer to your original code:

require('./app').default();

这篇关于在 Babel 6.x 中不能 require() 默认导出值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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