# 使用Typescript
# 安装
在命令行运行以下命令,全局安装
// yarn
yarn global add typescript
// npm
npm install -g typescript
安装完成后,检查是否成功
tsc -V // Version 版本号
# 编写
使用.ts
文件,编写js代码在浏览器可正常运行
// main.ts
(() => {
let str = 'Hello TS'
console.log(str)
// Hello TS
})()
编写ts代码在浏览器,报错
// main.ts
(() => {
let str: string = 'Hello TS'
console.log(str)
// 报错
})()
# 编译
# 手动编译
在命令行运行ts编译器
tsc main.ts
会自动生成main.js
文件,包含由main.ts
编译的js代码
// main.js
(function () {
var str = 'Hello TS';
console.log(str);
})();
# 测试下
在index.html引入main.js,浏览器控制台输出
Hello TS
在命令行运行
node main.js
//输出
Hello TS
# vscode自动编译
1. 命令行运行以下命令,生成配置文件tsconfig.json
tsc --init
2. 修改tsconfig.json文件
"outDir": "./js", // 编译成功文件输出目录
"strict": false, // 关闭严格模式
3. 启动监视任务
vscode工具栏: 终端 -> 运行任务 -> 监视tsconfig.json
4. 自动编译,生成js文件
# webpack打包TS
# 准备一个简单项目,结构如下
.
├── webpack-ts
│ ├── build
│ │ └── webpack.config.js
│ ├── public
│ │ └── index.html
│ └── src
│ └── main.ts
└── package.json
# index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>webpack-ts</title>
</head>
<body>
</body>
</html>
# main.ts
(() => {
console.log('Hello TS')
})()
# webpack.config.js
❗️ 不同版本的webpack配置有差异
const {CleanWebpackPlugin} = require('clean-webpack-plugin')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const path = require('path')
const isProd = process.env.NODE_ENV === 'production' // 是否生产环境
function resolve (dir) {
return path.resolve(__dirname, '..', dir)
}
module.exports = {
mode: isProd ? 'production' : 'development',
entry: {
app: './src/main.ts'
},
output: {
path: path.resolve('dist'),
filename: '[name].[contenthash:8].js'
},
module: {
rules: [
{
test: /\.tsx?$/,
use: 'ts-loader',
include: [resolve('src')]
}
]
},
plugins: [
new CleanWebpackPlugin({
}),
new HtmlWebpackPlugin({
template: './public/index.html'
})
],
resolve: {
extensions: ['.ts', '.tsx', '.js']
},
devtool: isProd ? 'cheap-module-source-map' : 'eval-cheap-module-source-map',
stats: 'errors-only', // 打包日志输出输出错误信息
devServer: {
host: 'localhost',
port: 8081,
open: true
},
}
# 安装依赖
yarn add -D typescript
yarn add -D ts-loader
yarn add -D webpack webpack-cli
yarn add -D webpack-dev-server
yarn add -D html-webpack-plugin clean-webpack-plugin
yarn add -D cross-env
# 配置打包命令
// package.json
"scripts": {
"dev": "cross-env NODE_ENV=development webpack-dev-server --config build/webpack.config.js",
"build": "cross-env NODE_ENV=production webpack --config build/webpack.config.js"
},
# 打包运行
yarn dev
yarn build