步骤
一、初始化项目
进入项目根目录,执行命令
npm init -y
,创建package.json文件下载工具
二、下载配置工具
npm i -D webpack webpack-cli webpack-dev-server typescript ts-loader clean-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的配置文件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/index.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"]
},
module: {
rules: [
{
test: /\.ts$/,
use: {
loader: "ts-loader"
},
exclude: /node_modules/
}
]
},
plugins: [
new CleanWebpackPlugin(),
new HtmlWebpackPlugin({
title:'TS测试'
}),
]
}
四、配置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"
},
...
}
六、项目使用
- 执行
npm run build
对代码进行编译;- 或者执行
npm start
来启动开发服务器;