【问题标题】:Running a single file as ESM with typescript without changing package.json在不更改 package.json 的情况下使用打字稿将单个文件作为 ESM 运行
【发布时间】: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


    【解决方案1】:

    我有一个类似的问题。我的解决方案是在 tsconfig.json 文件中使用 "moduleTypes" 配置选项。您可以提供 glob -> module-type-override 的查找。

    对于您的示例,请在您的tsconfig.json 中尝试此操作:

    {
      "ts-node": {
        "moduleTypes": {
          "lib/cache.ts": "esm"
        }
      }
    }
    

    有关详细信息,请参阅文档:https://typestrong.org/ts-node/docs/module-type-overrides/

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-03-22
      • 2017-05-21
      • 2021-04-16
      • 2015-08-08
      • 2020-11-21
      • 2015-10-10
      • 2020-04-01
      相关资源
      最近更新 更多