返回 old(m, filename);错误 [ERR_REQUIRE_ESM]:ES 模块的 require()

return old(m, filename); Error [ERR_REQUIRE_ESM]: require() of ES Module

提问人:Lucas Amorim Lima 提问时间:1/21/2022 更新时间:10/10/2023 访问量:18024

问:

我正在尝试与 Unsplash API 进行集成,但我得到,

当我尝试通过ts-node运行脚本时,例如:

ts-node unsplash.ts

存在以下错误:

C:\Users\USER\AppData\Roaming\npm\node_modules\ts-node\dist\index.js:729
            return old(m, filename);
                   ^
Error [ERR_REQUIRE_ESM]: require() of ES Module C:\Users\USER\Desktop\tindin\node_modules\node-fetch\src\index.js from C:\Users\USER\Desktop\tindin\src\api\services\unsplash.ts not supported.
Instead change the require of index.js in C:\Users\USER\Desktop\tindin\src\api\services\unsplash.ts to a dynamic import() which is available in all CommonJS modules.
    at Object.require.extensions.<computed> [as .js] (C:\Users\USER\AppData\Roaming\npm\node_modules\ts-node\dist\index.js:729:20)
    at Object.<anonymous> (C:\Users\USER\Desktop\tindin\src\api\services\unsplash.ts:23:30)
    at Module.m._compile (C:\Users\USER\AppData\Roaming\npm\node_modules\ts-node\dist\index.js:735:29)
    at Object.require.extensions.<computed> [as .ts] (C:\Users\USER\AppData\Roaming\npm\node_modules\ts-node\dist\index.js:737:16)
    at main (C:\Users\USER\AppData\Roaming\npm\node_modules\ts-node\dist\bin.js:238:16)
    at Object.<anonymous> (C:\Users\USER\AppData\Roaming\npm\node_modules\ts-node\dist\bin.js:351:5) {
  code: 'ERR_REQUIRE_ESM'
}

我的代码

import { createApi } from 'unsplash-js';
import * as nodeFetch from 'node-fetch'

const unsplash = createApi({
  accessKey: 'MY_ACCESS_KEY',
  fetch: nodeFetch.default as unknown as typeof fetch,
});

我正在遵循 Unsplash 文档本身的参考 友情链接 : https://github.com/unsplash/unsplash-js

我的package.json

{
  "name": "typescript",
  "version": "1.0.0",
  "main": "server.js",
  "license": "MIT", 
  
  "scripts": {
    "dev": "ts-node-dev --inspect --transpile-only --ignore-watch node_modules src/server.ts",
    "lint": "eslint . --ext .ts",
    "lint-fix": "eslint . --ext .ts --fix"
  },
  "devDependencies": {
    "@types/node": "^17.0.8",
    "@typescript-eslint/eslint-plugin": "^5.9.0",
    "@typescript-eslint/parser": "^5.9.0",
    "eslint": "^8.6.0",
    "ts-node-dev": "^1.1.8",
    "tsconfig-paths": "^3.12.0",
    "typescript": "^4.5.4"
  },
  "dependencies": {
    "node-fetch": "^3.1.1",
    "unsplash-js": "^7.0.15"
  }
}
  

我的tsconfig.json

{
  "compilerOptions": {
   
    "target": "es5",                          /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */
    "module": "commonjs",                     /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */
    "allowJs": true,                          /* Allow javascript files to be compiled. */
    "outDir": "./build",                        /* Redirect output structure to the directory. */
    "rootDir": "./src",                         /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
    "strict": true,                           /* Enable all strict type-checking options. */
    "noImplicitAny": true,                    /* Raise error on expressions and declarations with an implied 'any' type. */
    "strictPropertyInitialization": false,  /* Enable strict checking of property initialization in classes. */

    /* Module Resolution Options */
    "moduleResolution": "node",            /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
    "baseUrl": ".",                       /* Base directory to resolve non-absolute module names. */
   
    "esModuleInterop": true,                  /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */

    /* Experimental Options */
    "experimentalDecorators": true,        /* Enables experimental support for ES7 decorators. */
    "emitDecoratorMetadata": true,         /* Enables experimental support for emitting type metadata for decorators. */

    /* Advanced Options */
    "resolveJsonModule": true,                /* Include modules imported with '.json' extension */
    "forceConsistentCasingInFileNames": true, /* Disallow inconsistently-cased references to the same file. */
  },
  "exclude": [
    "node_modules",
    "build"
  ],
  "include": [
    "src/**/*"
  ]
}

我在package.json文件中添加了 “type”: “module”。

{
  "name": "typescript",
  "version": "1.0.0",
  "type": "module",
...
}

我收到此错误

TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension ".ts" for C:\Users\USER\Desktop\tindin\src\api\services\unsplash.ts
    at new NodeError (node:internal/errors:371:5)
    at Object.file: (node:internal/modules/esm/get_format:72:15)
    at defaultGetFormat (node:internal/modules/esm/get_format:85:38)
    at defaultLoad (node:internal/modules/esm/load:13:42)
    at ESMLoader.load (node:internal/modules/esm/loader:303:26)
    at ESMLoader.moduleProvider (node:internal/modules/esm/loader:230:58)
    at new ModuleJob (node:internal/modules/esm/module_job:63:26)
    at ESMLoader.getModuleJob (node:internal/modules/esm/loader:244:11)
    at async Promise.all (index 0)
    at async ESMLoader.import (node:internal/modules/esm/loader:281:24) {
  code: 'ERR_UNKNOWN_FILE_EXTENSION'
}
JavaScript 节点.js 打字稿

评论

0赞 tromgy 1/21/2022
您可以尝试更改为 in tsconfig.json"module": "commonjs""module": "esnext"
1赞 Lucas Amorim Lima 1/21/2022
@tromgy不起作用,替换到“module”:“esnext”,继续出现相同的错误未知文件扩展名“.ts”
1赞 tromgy 1/21/2022
这似乎是 ts-node 臭名昭著的“catch-22”问题。您可以检查此 stackoverflow 线程。我认为您最好的选择是先编译,然后使用节点运行生成的 .js 文件。保持package.jsontsconfig.json"type": "module""module": "esnext"

答:

1赞 Daniel 3/13/2023 #1

我使用以下指令进行了修复:

https://github.com/TypeStrong/ts-node/issues/1007

建议阅读更广泛的背景信息:

https://gist.github.com/sindresorhus/a39789f98801d908bbc7ff3ecc99d99c

总结:

  1. tsconfig.json
    "module": "ESNext",                                  /* Specify what module code is generated. */
    "moduleResolution": "node",                       /* Specify how TypeScript looks up a file from a given module specifier. */
  1. package.json
  "type": "module",
  1. 更改节点内置模块的默认导入,例如:
import os from 'os';

import {homedir} from 'os';

import fs from 'fs';

import {existsSync, readFileSync, writeFileSync} from 'fs';
  1. 使用标志运行--esm
npx ts-node --esm src/index.ts

类似问题:

评论

1赞 khokm 5/1/2023
此解决方案不适用于打字稿路径映射:github.com/khokm/ts-node-esm-paths-problem