#目录结构
1、在终端 进入项目目录 按顺序依次执行下面每行代码
npm init -y
tsc --init
npm install -D typescript
npm install -D webpack webpack-cli
npm install -D webpack-dev-server
npm install -D html-webpack-plugin clean-webpack-plugin
npm install -D ts-loader
npm install -D cross-env
2、创建 /build/webpack.config.js 配置文件
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: 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: 'cheap-module-source-map',
devServer: {
host: 'localhost', // 主机名
port: 8081,
open: true
},
}
3、创建 /public/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>webpack & TS</title>
</head>
<body>
</body>
</html>
4、创建 /src/main.ts 入口文件
console.log(1);
5、修改 /package.json 中的"scripts"内容
"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"
},
6、运行项目
命令行输入 npm run dev
7、打包项目
命令行输入 npm run build