【问题标题】:Module.exports and es6 ImportModule.exports 和 es6 导入
【发布时间】:2025-12-25 14:55:15
【问题描述】:

与 babel 反应。我对导入和 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");

我使用带有预设 es2015 的 babel 进行转编译。这给了我以下错误

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

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

我在这里错过了什么??

编辑: 我正在使用 browserify 作为模块捆绑器。

【问题讨论】:

  • 你看过 Babel 输出了吗?查看Tiger.js 的转译源代码会立即告诉您为什么它不起作用。长话短说:坚持使用一个模块系统或使用像 webpack 这样的模块打包器来处理不一致。
  • 对不起,我使用 browserify 作为模块捆绑器

标签: javascript babeljs es6-module-loader


【解决方案1】:

export { Tiger } 将等同于 module.exports.Tiger = Tiger

相反,module.exports = Tiger 将等效于 export default Tiger

因此,当您使用module.exports = Tiger 然后尝试import { Tiger } from './animals' 时,您实际上是在请求Tiger.Tiger

【讨论】:

  • 那么正确的导入语句应该是什么?会不会只是import Tiger from './animals'
  • 我相信是的,假设你不想改变tiger.js
【解决方案2】:

如果您想导入:

module.exports = Tiger

你可以使用以下结构:

import * as Tiger from './animals'

然后就可以了。

另一种选择是按照@Matt Molnar 的描述更改导出,但只有当您是导入代码的作者时才有可能。

【讨论】:

  • import * as Tiger from './animals' 为我工作!谢谢
  • Tiger 是上例中的一个函数。您不能使用import * as something 导入可调用(函数或类),因为something 将代表一个不可调用的namespace 对象。这种情况下的正确导入将是默认导入:import Tiger from './animals';
【解决方案3】:

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

命名导入/导出:

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

// animal.js
import { tiger } from './tiger';

【讨论】:

  • 为你的答案添加一些解释
  • 是的,我的错。我的回答只是在已经解释的内容之外添加更多解决方案。