CommonJS 和 ES Module 终于能够互相兼容了
warning:
这篇文章距离上次修改已过289天,其中的内容可能已经有所变动。
自从CommonJS和ES Modules在Node.js中可以互相兼容以来,这两种模块系统的互操作性已经得到了显著改善。在Node.js中,你现在可以在相同的项目中混合使用这两种模块系统,而不会遇到之前的问题。
例如,如果你想在CommonJS模块中导入一个ES Module,你可以使用.js
扩展名并在import
语句中使用require
函数:
// ES Module (example.js)
export function hello() {
return 'Hello, world!';
}
// CommonJS (index.js)
const example = require('./example.js');
console.log(example.hello()); // 输出: Hello, world!
反过来,在ES Module中导入CommonJS模块时,你可以直接使用import
语句,但需要确保CommonJS模块可以被正确地转换为ES Module。这通常是通过在文件顶部添加"type": "module"
到包的package.json
或者使用.mjs
扩展名来实现的。
// CommonJS (logger.cjs)
module.exports = {
log: (message) => console.log(message);
};
// ES Module (index.js)
import logger from './logger.cjs';
logger.log('Hello, world!'); // 输出: Hello, world!
在实际的应用程序中,你可以混合使用这两种模块系统,并且可以使用转换工具(如esm)来确保CommonJS模块可以以ES Module的形式被导入。
评论已关闭