【发布时间】:2022-12-22 20:28:50
【问题描述】:
我以前遇到过这个问题,直到现在我才回到 JS,但我想最终一劳永逸地解决它。不幸的是,感觉就像我在兜圈子,所以我很感激任何帮助。
我正在尝试在 Typescript Next.js 项目中使用单文件脚本。该脚本应该通过ts-node 运行并缓存一些静态内容。无论哪种方式,它都是一个独立于项目核心的实体。
我用这个命令运行脚本:
"cache": "ts-node --project lib/script.tsconfig.json lib/cache.ts",
我的 tsconfig 看起来像这样:
{
"compilerOptions": {
"module": "commonjs",
"esModuleInterop": true
}
}
该脚本一直有效,直到它开始使用从 ESM 导入的函数。在这一点上它崩溃了:
// this is an ESM
import { serialize } from 'next-mdx-remote/serialize'
const cache = () => {
// other logic
serialize();
}
错误:
Error [ERR_REQUIRE_ESM]: require() of ES Module /project/wordpress-react/node_modules/next-mdx-remote/serialize.js from /project/wordpress-react/lib/cache.ts not supported.
Instead change the require of serialize.js in /project/wordpress-react/lib/cache.ts to a dynamic import() which is available in all CommonJS modules.
现在,我用谷歌搜索了这个,实际上每个答案都告诉我添加
"type": "module"
到我的 package.json。但是,如果我这样做,我的 Next.js 项目就会停止工作:
error - Failed to load next.config.js, see more info here https://nextjs.org/docs/messages/next-config-error
ReferenceError: module is not defined in ES module scope
This file is being treated as an ES module because it has a '.js' file extension and '/project/wordpress-react/package.json' contains "type": "module". To treat it as a CommonJS script, rename it to use the '.cjs' file extension.
如何在不破坏项目其余部分的情况下让我的脚本正常工作?当然必须有办法吗?
【问题讨论】:
标签: javascript node.js typescript