使用ts-node命令运行ts文件时报错(Warning: To load an ES module, set “type“: “module“ in the package.json...)

使用ts-node命令运行ts文件时报错(Warning: To load an ES module, set “type“: “module“ in the package.json...),第1张

使用 ts-node 运行TS文件时报错。

错误信息1:

E:\PersonalProject\ts-utils\test>ts-node DateChainTest.ts
(node:22636) Warning: To load an ES module, set "type": "module" in the package.json or use the .mjs extension.
(Use `node --trace-warnings ...` to show where the warning was created)
E:\PersonalProject\ts-utils\test\DateChainTest.ts:1
import { DateChain } from '../src/DateChain';
^^^^^^

SyntaxError: Cannot use import statement outside a module

......

错误信息2:

TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension ".ts" for E:\PersonalProject\ts-utils\test\DateChainTest.ts
    at new NodeError (node:internal/errors:371:5)
    at Loader.defaultGetFormat [as _getFormat] (node:internal/modules/esm/get_format:71:15)
    at Loader.getFormat (node:internal/modules/esm/loader:105:42)
    at Loader.getModuleJob (node:internal/modules/esm/loader:243:31)
    at async Loader.import (node:internal/modules/esm/loader:177:17)
    at async Object.loadESM (node:internal/process/esm_loader:68:5)
    at async handleMainPromise (node:internal/modules/run_main:63:12) {
  code: 'ERR_UNKNOWN_FILE_EXTENSION'
}

ts-node 版本:^10.8.0typescript 版本:^4.6.3

tsconfig.json文件内容如下

{
  "compilerOptions": {
    "baseUrl": "./",
    "module": "es6",
    "target": "es2020",
    "allowJs": false,
    "declaration": true,
    "outDir": "./dist",
    "strict": true
  },
  "exclude": [
    "node_modules"
  ],
  "include": [
    "index.ts",
    "src/*"
  ]
}

在网上查找了一些资料,出现类似问题的有很多,链接如下:

http://www.longant.cn/en/node/7289https://stackoverflow.com/questions/62096269/cant-run-my-node-js-typescript-project-typeerror-err-unknown-file-extensionhttps://www.npmjs.com/package/ts-node?activeTab=readme#commonjs

其中主要有以下几种解决方式:

方法1:

package.json中设置"type"属性为"module";再将tsconfig.json中的compilerOptionsesModuleInterop属性值置为true。 尝试结果:失败,报错信息内容如错误信息2所示

方法2:

package.json中移除"type": "module";在tsconfig.json中将compilerOptionsmodule属性改为"CommonJS",或者在该文件中添加"ts-node"配置项。
{
  /* ... your props ... */
  "ts-node": {
    "compilerOptions": {
      "module": "CommonJS"
    }
  }
}
尝试结果:成功,问题解决!!!

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/1322051.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-12
下一篇 2022-06-12

发表评论

登录后才能评论

评论列表(0条)

保存