安装:
npm i -g typescript
解决Vscode禁止脚本运行
管理员运行Vscode
打开终端输入
get-ExecutionPolicy
set-ExecutionPolicy RemoteSigned
编译运行
- 编译指定文件
tsc —outDir 输出文件的目录 要编译的ts文件
- 以指定版本编译ts文件
tsc —outDir 输出文件的目录 —target es3/es5/es6 要编译的ts文件
- 持续监听文件变化并编译
tsc —outDir 输出文件的目录 —target es3/es5/es6 —watch 要编译的ts文件
编译配置文件
在前面的基础上我们可以配置一个tsconfig.json文件 来便捷的配置ts文件编译
{
"compilerOptions":{
"outDir":"../dist",
"target":"es6", //指定编译版本
"watch":true,
"moduleResolution": "node", //解决node报错
"strictNullChecks": true, //严格检测null类型赋值报错
"noImplicitAny":true //严格检测any类型的函数参数定义
},
"include":["../src/**/*"]
}
使用指定的编译配置文件运行
tsc - p 编译文件或者目录
编译报错
Cannot find module ‘vite’. Did you mean to set the ‘moduleResolution’ option to ‘node’, or to add aliases to the ‘paths’ option?
在配置文件中写入:
{
"compilerOptions":{
+ "moduleResolution": "node"
},
"include":["../src/**/*"]
}
配置ts webpack运行环境
开发依赖和环境
"devDependencies": {
"html-webpack-plugin": "^5.5.0",
"ts-loader": "^9.2.8",
"typescript": "^4.6.2",
"webpack": "^5.70.0",
"webpack-cli": "^4.9.2",
"webpack-dev-server": "^4.7.4"
}
"scripts": {
"build": "webpack",
"serve": "webpack serve"
}
webpack配置:
const HtmlWebpackPlugin = require('html-webpack-plugin')
const path = require('path')
module.exports = {
mode: "development",
entry: "./src/main.ts",
output: {
path: path.resolve(__dirname, 'dist'),
filename: "dist/bundle.js"
},
resolve: {
extensions: ['.ts', '.js', '.json']
},
module: {
rules: [
{
test: /\.ts$/,
loader: 'ts-loader'
}
]
},
plugins: [
new HtmlWebpackPlugin({
template: "./index.html"
})
]
}
运行结构: