如何在 CJS-first 项目中从扩展名为 .mts 的文件导入?

问题描述 投票:0回答:1

所以我这里有一个 fetchin.mts 文件:

import type { RequestInfo, RequestInit, Response } from "node-fetch";
const importDynamic = new Function("modulePath", "return import(modulePath);")

export async function fetch(url: URL | RequestInfo, init?: RequestInit) : Promise<Response> {
  const {default: fetch} = await importDynamic("node-fetch");
  return fetch(url, init);
}

当我尝试在另一个文件上导入 fetch 函数时,如下所示:

import {fetch} from "../utils/fetchin.mjs"

我收到 ts 错误:

The current file is a CommonJS module whose imports will produce 'require' calls; however, the referenced file is an ECMAScript module and cannot be imported with 'require'. Consider writing a dynamic 'import("../utils/fetchin.mjs")' call instead.
  To convert this file to an ECMAScript module, change its file extension to '.mts', or add the field `"type": "module"` to '/package.json'.ts(1479)

我已经尝试过将

"type": "module"
放在包 json 上的建议,但将其导入到另一个文件时仍然无法修复 ts 错误,并尝试在谷歌上研究这些东西,但我找不到任何关于它的参考

这是我的 tsconfig.json 文件:

{
  "extends": "@tsconfig/node18/tsconfig.json",
  "compilerOptions": {
    "removeComments": false,
    "preserveConstEnums": true,
    "outDir": "lib/",
    "sourceMap": true,
    "esModuleInterop": true,
    "strict": true
  },
  "ts-node": {
    "files": ["src/types/modules.d.ts"],
  }
}

我还看到一些文章说我需要将 tsconfig/node18 降级到 tsconfig/node16 但我仍然不明白。帮助大家!

javascript node.js typescript es6-modules commonjs
1个回答
0
投票

您还没有真正说明导入

fetch
的其他文件正在使用什么文件扩展名,但我假设它是
.ts
扩展名,并且您的 package.json 正在使用
"type": "commonjs"
(或未指定) ,因此默认为 CJS)。我还将忽略
ts-node
的使用并专注于
tsc

这是 tsconfig.json (和你的一样,但没有 ts-node 的东西):

{
  "extends": "@tsconfig/node18/tsconfig.json",
  "compilerOptions": {
    "removeComments": false,
    "preserveConstEnums": true,
    "outDir": "lib/",
    "sourceMap": true,
    "esModuleInterop": true,
    "strict": true
  }
}

简单的修复方法是在 package.json 中使用

"type": "module"
。然后只需运行
./node_modules/.bin/tsc
即可成功构建。我知道你说过你尝试过这个,但你一定忽略了一些东西,因为这确实有效。

如果您想继续使用 CJS,即

"type": "commonjs"
,请在从
fetch
文件导入
.mts
时使用动态导入。

让我们调用另一个文件

other.ts

const importFetch = async () => {
  const { fetch } = await import('./fetchin.mjs')
}

importFetch()

现在像以前一样再次运行

tsc
即可成功构建,或者运行
ts-node other.ts
。顺便说一下,这正是错误消息所建议的。

© www.soinside.com 2019 - 2024. All rights reserved.