初始化项目
npm init -y
下载构建工具
npm i -D webpack webpack-cli webpack-dev-server typescript ts-loader clean-webpack-plugin
npm install html-webpack-plugin
webpack
构建工具webpack
webpack-cli
webpack的命令行工具
webpack-dev-server
webpack的开发服务器
typescript
ts编译器
ts-loader
ts加载器,用于在webpack中编译ts文件
html-webpack-plugin
webpack中html插件,用来自动创建html文件
clean-webpack-plugin
webpack中的清除插件,每次构建都会先清除目录
根目录下创建webpack的配置文件webpack.config.js
const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const { CleanWebpackPlugin } = require("clean-webpack-plugin");
module.exports = {
optimization:{
minimize: false // 关闭代码压缩,可选
},
// 指定入口文件
entry: "./src/main.ts",
devtool: "inline-source-map",
devServer: {
contentBase: './dist'
},
// 指定打包文件所在目录
output: {
path: path.resolve(__dirname, "dist"),
filename: "bundle.js",
environment: {
arrowFunction: false // 关闭webpack的箭头函数,可选
}
},
resolve: {
extensions: [".ts", ".js"]
},
mode: 'development',
// 指定webpack打包时要使用模板
module:{
// mode: 'development',
// 指定要加载的规则
rules: [
{
// test指定的是规则生效的文件
test: /\.ts$/,
// 要使用的loader
use: {
loader: "ts-loader"
},
// 要排除的文件
exclude: /node_modules/
}
]
},
plugins: [
new CleanWebpackPlugin(),
new HtmlWebpackPlugin({
title:'TS测试'
}),
]
}
根目录下创建tsconfig.json,配置可以根据自己的需要去修改添加
{
"compilerOptions": {
"target": "ES2015",
"module": "ES2015",
"strict": true
}
}
修改package.json添加如下配置
{
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"build": "webpack",
"start": "webpack serve --open chrome.exe"
},
}