为什么在不能在TypeScript项目执行.ts文件?
我想要封装一个类,并且使用ts-node执行:
src/index.ts
class Animal {
readonly age: number = 0
readonly name: string | undefined = undefined
constructor(age: number, name: string) {
this.age = age
this.name = name
}
}
export class Person extends Animal {
readonly height: number
constructor(age: number, name: string, height: number) {
super(age, name)
this.height = height
}
}
test/testPerson.ts
import { Person } from '../src/index';
const p = new Person(25, 'John', 177)
console.log(p)
export default {}
我运行ts-node 执行 测试文件报错:不识别.ts后缀的文件:
$ ts-node test/personTest.ts
TypeError: Unknown file extension ".ts" for /Users/user/Desktop/Test/Test-demos/nodejs-test-demos/nodejs-demo-04-npmpackage/test/personTest.ts
at Object.getFileProtocolModuleFormat [as file:] (node:internal/modules/esm/get_format:160:9)
at defaultGetFormat (node:internal/modules/esm/get_format:203:36)
at defaultLoad (node:internal/modules/esm/load:143:22)
at async ModuleLoader.load (node:internal/modules/esm/loader:403:7)
at async ModuleLoader.moduleProvider (node:internal/modules/esm/loader:285:45)
at async link (node:internal/modules/esm/module_job:78:21) {
code: 'ERR_UNKNOWN_FILE_EXTENSION'
}
我按照网上说的,找到package.json 删除:"type": "module",
但是又会报其他错误:
import { Person } from '../src/index';
^^^^^^
SyntaxError: Cannot use import statement outside a module
at internalCompileFunction (node:internal/vm:128:18)
at wrapSafe (node:internal/modules/cjs/loader:1280:20)
at Module._compile (node:internal/modules/cjs/loader:1332:27)
at Module.m._compile (/Users/user/Library/pnpm/global/5/.pnpm/ts-node@10.9.2_@types+node@20.12.13_typescript@5.4.5/node_modules/ts-node/src/index.ts:1618:23)
at Module._extensions..js (node:internal/modules/cjs/loader:1427:10)
at Object.require.extensions.<computed> [as .ts] (/Users/markleo/Library/pnpm/global/5/.pnpm/ts-node@10.9.2_@types+node@20.12.13_typescript@5.4.5/node_modules/ts-node/src/index.ts:1621:12)
at Module.load (node:internal/modules/cjs/loader:1206:32)
at Function.Module._load (node:internal/modules/cjs/loader:1022:12)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:135:12)
at phase4 (/Users/user/Library/pnpm/global/5/.pnpm/ts-node@10.9.2_@types+node@20.12.13_typescript@5.4.5/node_modules/ts-node/src/bin.ts:649:14)
请问:
1、package.json内"type": "module",
的作用是什么呢?
2、我想要到时候打包上传npmjs.org,这个配置"type": "module",
会不会有影响呢?
3、SyntaxError: Cannot use import statement outside a module
这个错误如何解决呢?
在 tsconfig.json 中添加:
运行:
ts-node-esm script.ts