ES Module和CommonJS同时使用
ES Modules 中使用 Common.js 规范文件
在 ES Module 中可以载入 Common.js 标准的模块。
// Common.js
module.exports = {
foo: "commonjs exports value",
};
// exports.foo = 'commonjs exports value'; // 别名使用
// es-module.mjs
import mod from "./commonjs.js";
console.log(mod); // { foo: 'commonjs exports value' }
// import { foo } from './commonjs.js'
// console.log(foo); // commonjs exports value
在 Common.js 规范文件中使用 ES Modules
在 Node.js 的原生环境中是==不允许==通过 CommonJS 模块来载入 ES Modules 的。
// Common.js
export const foo = "es module export value";
// es-module.mjs
const mod = require("./es-module.mjs");
console.log(mod); // error