繁体   English   中英

使用 typescript 时“不支持 ES 模块 [...] 的 require()”

[英]"require() of ES Module [...] is not supported" when using typescript

我的设置如下:

我有一个package.json文件:

{
  "name": "discord-app-test",
  "version": "1.0.0",
  "main": "src/index.ts",
  "license": "ISC",
  "scripts": {
    "dev": "nodemon --exec \"yarn start\" --watch src --ext ts,json --ignore *.test.ts",
    "start": "ts-node ."
  },
  "dependencies": {
    "dotenv": "^10.0.0",
    "node-fetch": "^3.0.0"
  },
  "devDependencies": {
    "@types/node": "^16.11.6"
  }
}

我没有tsconfig.json文件,因为我通常不需要它。 虽然,不知何故,当使用node-fetch package 时,我收到此错误消息“ require() of ES Module [...] is not supported ”,即使我使用 ES6 语法导入它:

import fetch from 'node-fetch';

我曾尝试在我的 package.json 中指定"type": "module" ,但随后出现错误“ Unknown file extension ".ts" for [...] ”。

您可能想使用"type": "module"因为这是在节点中导入内容的新方法。 使用此标志,您可以告诉节点使用 ESM 进行导入,这是您在问题中使用的语法。

ESM 是相当新的,因此大多数工具都可以选择加入, ts-node也是如此,您必须添加--esm参数。

$ ts-node --esm ./index.ts

运行这个仍然失败

$ ts-node --esm ./index.ts
ReferenceError: exports is not defined in ES module scope
    at file:///path/to/index.ts:5:23
    at ModuleJob.run (node:internal/modules/esm/module_job:194:25)

该错误是因为ts-node内部使用的tsc s --module default。

--target : 默认值:ES3

--module :如果目标是 ES3 或 ES5,则默认为 CommonJS,否则为 ES6/ES2015。

https://www.typescriptlang.org/docs/handbook/compiler-options.html

tsc会将脚本转译为 CommonJS,因为--target默认是 ES3 然后--module默认是 CommonJS。

您可以通过手动运行 TypeScript 编译器来检查这一点。

索引.ts

import fetch from "node-fetch";
fetch("https://example.org");
$ tsc ./index.ts

index.js(由 tsc 创建)

"use strict";
exports.__esModule = true;
var node_fetch_1 = require("node-fetch");
(0, node_fetch_1["default"])("https://example.org");

.ts 文件是为 CommonJS 转译的(它使用require )。

当您在package.json中定义"type": "module"时,您告诉节点使用新的导入语法,但 tsc 忽略它并仍然以旧格式输出它。

如果你想在节点中本地使用新的导入语法,那么你可以通过将模块定义为nodenext来解决这个问题,它描述了节点的 ESM 支持。

$ tsc --module nodenext ./index.ts

index.js(由 tsc 创建)

import fetch from "node-fetch";
fetch("https://example.org");

ts-node配置--module的最简单方法是使用以下内容创建tsconfig.json

{
  "compilerOptions": {
    "module": "nodenext"
  },
  "include": ["*.ts"]
}

现在,在配置模块后,您可以运行ts-node ,它有望正常运行。

$ ts-node --esm ./index.ts

在这里你可以阅读更多关于ts-node中的 ESM 支持: https://github.com/TypeStrong/ts-node/issues/1007

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM