我有一个Node.js TypeScript项目(AWS函数),它已经正确工作了好几个月。但是,我最近需要添加得到包,这是一个ES模块,现在我试图运行这个被转移的项目,结果是:
require() of ES modules is not supported.
require() of *REDACTED*/node_modules/got/dist/source/index.js from *REDACTED*/my-lambda/handler/list-api.js is an ES module file as it is a .js file whose nearest parent package.json contains "type": "module" which defines all .js files in that package scope as ES modules.这是有意义的,从nodemodules/got/package.json,内部看,这个包确实是一个ES模块("type": "module"__)。然而,我无法想出一个tsconfig.json版本,它允许我导入这个模块,而不是强迫我以丑陋的方式更新我的应用程序代码(见下文)或捆绑它(这显然是lambda的一个问题)。
谁能告诉我在一个节点项目中支持ES模块tsconfig.json in node_modules的一个正在工作的node_modules
我的tsconfig.json的原始工作版本
(在添加got和解决问题的各种尝试之前)
{
"compilerOptions": {
"moduleResolution": "Node",
"esModuleInterop": true,
"noImplicitAny": true,
"sourceMap": true,
"outDir": "handler",
"baseUrl": ".",
"paths": {
"*": ["node_modules/*"]
},
"strict": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"declaration": true
},
"include": ["src/**/*"]
}一个可行的“解决方案”是将我的lambda也转换为ES模块("type": "module" in package.json),并将tsconfig.json中的“模块”和"target“设置为esnext。这将在功能上起作用,但也迫使我在项目中的所有相关导入中添加.js后缀,这在TypeScript文件中非常奇怪,而且很难阅读。我还担心,在使用较早版本的Node的环境中,这可能无法正常工作。
捆绑webpack和ts-loader也有效,但显然破坏了Lambda的层/处理程序分离。
非常感谢你的任何想法!
发布于 2022-03-22 17:42:59
他们的自述说:
警告:此包是本机ESM,不再提供CommonJS导出。如果项目使用CommonJS,则必须转换为ESM或使用dynamic ()函数。请不要公开有关CommonJS / ESM的问题。您也可以使用Got v11,这是相当稳定的。
您可以通过import()导入模块。
import('got').then((module) => {
const { default: got } = module;
/* same got as in */
/* import got from 'got'; */
got.post(...) //etcetera
});或者您只需使用他们使用的最后一个版本,使用cjs (11.0)
npm install got@11https://stackoverflow.com/questions/71576397
复制相似问题