[英]Module.exports and es6 Import
与 babel 反应。 我对导入和 module.exports 有这种困惑。 我假设 babel 在将 ES6 代码转换为 ES5 时将导入和导出分别转换为 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 来编译它。 这给了我以下错误
Uncaught TypeError: (0 , _animals.Tiger) 不是函数
但是如果我删除module.exports = Tiger;
并将其替换为export { Tiger };
它工作正常。
我在这里错过了什么?
编辑:我使用 browserify 作为模块捆绑器。
export { Tiger }
等价于module.exports.Tiger = Tiger
。
相反, module.exports = Tiger
等同于export default Tiger
。
因此,当您使用module.exports = Tiger
然后尝试import { Tiger } from './animals'
您实际上是在要求Tiger.Tiger
。
如果您想导入:
module.exports = Tiger
您可以使用以下结构:
import * as Tiger from './animals'
然后它会起作用。
另一种选择是按照@Matt Molnar 的描述更改导出,但只有当您是导入代码的作者时才有可能。
当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';
对我来说,我正在尝试将其应用于webpack.config.ts。 以上内容不能import * as X from "./X";
我收到另一个错误。
Module.exports,带有es6导入,用于typescript中的webpack.config.ts
const getConfig = ( appDir: string, distDir: string, env: any, args: any ): webpack.Configuration => {
const config: webpack.Configuration = {
return config;
};
};
module.exports = getConfig;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.