我使用的是ts-node
,但是它给了我这个错误:
$ ts-node index.ts
TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension ".ts" for /home/projects/node-hddds8/index.ts
我试图从我的"type": "module"
中删除package.json
,但在这种情况下,我得到了一个不同的错误:
$ ts-node index.ts
(node:45) 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)
/home/projects/node-hddds8/index.ts:1
import chalk from 'chalk';
^^^^^^
SyntaxError: Cannot use import statement outside a module
下面是StackBlitz:https://stackblitz.com/edit/node-hddds8?file=index.ts上的一个复制链接
我的package.json如下所示:
{
"name": "node-starter",
"version": "0.0.0",
"type": "module",
"dependencies": {
"chalk": "^5.0.1",
"ts-node": "^10.8.1",
"typescript": "^4.7.4"
}
}
我的tsconfig.json看起来是这样的:
{
"compilerOptions": {
"target": "esnext",
"module": "esnext",
"moduleResolution": "Node",
}
}
我的index.ts看起来是这样的:
import chalk from 'chalk';
console.log(chalk.blue('Hello world!'));
发布于 2022-11-04 04:22:20
由于"type": "module"
在package.json
中使用,因此需要将其添加到tsconfig.json
中。
{
"compilerOptions": {
"module": "ESNext" // or ES2015, ES2020
},
"ts-node": {
// Tell ts-node CLI to install the --loader automatically
"esm": true
}
}
https://stackoverflow.com/questions/72796757
复制相似问题