写Typescript文件,node命令可以直接编运行,我们不想ts转换为js,再去执行
使用ts-node来支持,实现TS的Node运行环境,官网文档比较全面,查了博客朋友的方法都不是很好能解决自己的问题,后来还是仔细读了官方的英文文档,才完成了配置
官方文档:
官网给的,按着官网来就可以
# Locally in your project.
npm install -D typescript
npm install -D ts-node
# Or globally with TypeScript.
npm install -g typescript
npm install -g ts-node
# Depending on configuration, you may also need these
npm install -D tslib @types/node
在项目根目录创建tsconfig.json文件,具体的配置请移步tsconfig配置,我的配置文件如下所示:
{
"compilerOptions": {
"target": "esnext",
"module": "esnext",
"useDefineForClassFields": true,
"moduleResolution": "node",
"strict": true,
"jsx": "preserve",
"sourceMap": true,
"resolveJsonModule": true,
"esModuleInterop": true,
"lib": ["esnext", "dom"]
},
"include": [
"src/**/*.ts",
"src/**/*.d.ts",
"src/**/*.tsx",
"src/**/*.vue",
]
}
把这段ts-node的配置添加到tsconfig.json的配置文件中
源码compilerOptions 里的moudle是esnext的,我们不希望他全局修改,我们只希望使用ts-node的部分将ts文件使用CommonJS的方式编译执行
"ts-node": {
"compilerOptions": {
"module": "CommonJS"
}
}
官方文档说是让用node --loader ts-node/esm来执行
官方文档:https://github.com/TypeStrong/ts-node#commonjs-vs-native-ecmascript-modules
"scripts": {
...
"build:lib": "node --loader ts-node/esm ./mui-cli/src/commands/build.ts",
},
1、报错
(node:65039) 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)
/Users/likai/Documents/WebProject/ts-node-utils/handle-themes-file/main.ts:1
import HandleThemes from "./lib/HandleThemes";
^^^^^^
SyntaxError: Cannot use import statement outside a module
at wrapSafe (internal/modules/cjs/loader.js:979:16)
at Module._compile (internal/modules/cjs/loader.js:1027:27)
at Module.m._compile (/Users/likai/Documents/WebProject/ts-node-utils/node_modules/ts-node/src/index.ts:1311:23)
at Module._extensions..js (internal/modules/cjs/loader.js:1092:10)
at Object.require.extensions.<computed> [as .ts] (/Users/likai/Documents/WebProject/ts-node-utils/node_modules/ts-node/src/index.ts:1314:12)
at Module.load (internal/modules/cjs/loader.js:928:32)
at Function.Module._load (internal/modules/cjs/loader.js:769:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:72:12)
at main (/Users/likai/Documents/WebProject/ts-node-utils/node_modules/ts-node/src/bin.ts:331:12)
at Object.<anonymous> (/Users/likai/Documents/WebProject/ts-node-utils/node_modules/ts-node/src/bin.ts:482:3)
让在package.json中添加一个type类型为module的字段,这里不好用哈,看官网就知道了,为啥不好用了
其他参考