war*_*ahi 5 javascript commonjs node.js rollupjs mjs
我有一个后端 CJS 应用程序和一个前端 ESM 应用程序。以及我在 ESM 中创建的节点模块。节点模块非常适合我的 ESM 应用程序,因为它们都使用 ESMimport语法。尝试在 CJS 应用程序中使用它显然会引发错误,因为它无法读取 ESMimport语法。
我尝试使用Rollup.js将ESM代码转换为并在我的文件中CJS使用,但这不起作用。conditional exportspackage.json
假设它是一个像这样的库:
my-library.js
// No require on top. They will be local to their use.
const myLibrary = ...
// export default instead of module.exports
export default myLibrary
Run Code Online (Sandbox Code Playgroud)
该库必须首先将其扩展名重命名为 .mjs ("my-library.js" = "my-library.msj")
然后,
在 CJS (Node.js) =>
动态导入:
const {default: myUtilityLib } = await import("./my-library.mjs");
Run Code Online (Sandbox Code Playgroud)
在 ESM(浏览器)=>
像往常一样标准导入:
import myUtilityLib from "./my-library.mjs"
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1563 次 |
| 最近记录: |