全局安装typescript
npm i -g typescript
全局安装ts有利于方便的使用
调用npx tsc -h
可以查看tsc的帮助选项,选项中的大部分功能都可以通过配置文件设置,配置文件可以通过命令生成
npx tsc --init
// 成功后输出
// message TS6071: Successfully created a tsconfig.json file.
此时可通过npx tsc 来进行.ts文件的编译
安装webpack
npm i -D webpack webpack-cli webpack-dev-server
设置基础配置webpack.base.config.js
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry: './src/index.ts',
output: {
filename: 'app.js'
},
resolve: {
extensions: ['.js', '.ts', '.tsx']
},
module: {
rules: [
{
test: /\.tsx?$/i,
use: [{
loader: 'ts-loader'
}],
exclude: /node_modules/
}
]
},
plugins: [
new HtmlWebpackPlugin({
template: './src/template/index.html'
})
]
}
安装依赖
npm i ts-loader typescript html-webpack-plugin -D
在指定目录创建html模板
./src/template/index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>TypeScript in Action</title>
</head>
<body>
<div class="app"></div>
</body>
</html>
配置开发环境webpack.dev.config.js
module.exports = {
devtool: 'cheap-module-eval-source-map'
}
以上配置的source-map会忽略列信息,定位时会定位到ts源码
配置生产环境webpack.pro.config.js
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
module.exports = {
plugins: [
new CleanWebpackPlugin()
]
}
添加依赖
npm i -D clean-webpack-plugin
用于成功构建后清理构建目录
配置全局webpack
webpack.config.js
const merge = require('webpack-merge');
const baseConfig = require('./webpack.base.config');
const devConfig = require('./webpack.dev.config');
const proConfig = require('./webpack.pro.config');
const config = process.NODE_ENV === 'development' ? devConfig : proConfig;
module.exports = merge(baseConfig, config);
安装依赖
npm i -D webpack-merge
用于合并webpack配置
添加package脚本
"scripts": {
"start": "webpack-dev-server --mode=development --config ./build/webpack.config.js",
"build": "webpack --mode=production --config ./build/webpack.config.js",
"test": "echo \"Error: no test specified\" && exit 1"
},
脚本指定了当前环境的mode和使用的构建工具