Module.exports和es6导入

Nan*_*ani 25 babeljs es6-module-loader

与巴贝尔发生反应.我对import和module.exports感到困惑.在将ES6代码转换为ES5时,我假设babel将导入和导出分别转换为require和module.exports.

如果我从一个模块导出一个函数并在另一个模块中导入该函数,代码执行正常.但是如果我使用module.exports导出函数并使用"import"导入,则会在运行时抛出错误,表示它不是函数.

我做了一个例子.

// Tiger.js
function Tiger() {
    function roar(terrian){
        console.log('Hey i am in ' +  terrian + ' and i am roaing');
    };
    return roar;
}

module.exports = Tiger;

// animal.js
import { Tiger } from './animals';

var animal = Tiger();
animal("jungle");
Run Code Online (Sandbox Code Playgroud)

我使用预设es2015的babel进行反编译.这给了我以下错误

未捕获的TypeError:(0,_ animals.Tiger)不是函数

但是如果我删除它module.exports = Tiger;并用它替换export { Tiger };它工作正常.

我在这里失踪了什么?

编辑: 我使用browserify作为模块捆绑器.

Mat*_*nar 28

export { Tiger }相当于module.exports.Tiger = Tiger.相反,module.exports = Tiger相当于export default Tiger.因此,当您使用module.exports = Tiger然后尝试import { Tiger } from './animals'有效地要求时Tiger.Tiger.

  • 那么这里正确的导入声明是什么?难道只是“从‘./animals’导入老虎’”? (2认同)

jma*_*eli 18

如果您想导入:

module.exports = Tiger
Run Code Online (Sandbox Code Playgroud)

你可以使用以下结构:

import * as Tiger from './animals'
Run Code Online (Sandbox Code Playgroud)

然后它会工作.

另一种选择是改变@Matt Molnar所描述的导出,但只有你是导入代码的作者才有可能.

  • 来自'。/ animals'`的`import * as Tiger为我工作!谢谢 (2认同)
  • `Tiger` 是上面示例中的一个函数。您不能使用“import * as Something”导入可调用的(函数或类),因为“something”将表示一个不可调用的“命名空间”对象。这种情况下的正确导入是默认导入:`import Tiger from './animals';`。 (2认同)

Dan*_*ues 5

module.exports未设置时,它指向一个空对象 ( {})。当你这样做时module.exports = Tiger,你告诉运行时从该模块导出的Tiger对象是对象(而不是默认值{}),在这种情况下是一个函数。
由于您要导入相同的函数,因此导入的方法是使用默认导入 ( import tiger from './tiger')。否则,如果要使用命名导入(import { tiger } from './tiger'),则必须更改module.exports对象或使用export关键字而不是module.exports对象。

默认导入/导出:

// tiger.js
module.exports = tiger;
// or
export default function tiger() { ... }

// animal.js
import tiger from './tiger';
Run Code Online (Sandbox Code Playgroud)

命名导入/导出:

// tiger.js
module.exports = { tiger };
// or
module.exports.tiger = tiger
// or
export const tiger = () => { ... }
// or
export function tiger() => { ... }

// animal.js
import { tiger } from './tiger';
Run Code Online (Sandbox Code Playgroud)

  • 为你的答案添加一些解释 (3认同)