长话短说,我试图在 CommonJS 模块中使用一个只有 ES6 模块入口点的 npm 包,即 bids-validator
( GitHub ),作为我整个 50+模块 app 是用 CommonJS 构建的。根据 Node documentation ,执行此操作的标准方法是使用 import()
函数。我尝试了这种方法,代码如下:
async function importValidator() {
const { validate } = await import('bids-validator')
return validate
}
const validate = importValidator()
但是,这会导致 bids-validator
包出错,不一定是上面的导入函数:
error: unhandledRejection: Cannot use import statement outside a module
/*/app/api/node_modules/bids-validator/index.js:2
import validate from './validators'
有没有办法避免这种情况,以便我可以在 CommonJS 模块中使用该包?
最佳答案
检查您在 package.json 中选择了什么作为选项。确保选择类型:“common.js”而不是“模块”
关于javascript - 在 CommonJS Node 应用程序中导入 ES6 模块?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67137415/