安装依赖
npm install -D typescript
npm install -D webpack@4.41.5 webpack-cli@3.3.10 webpack-dev-server@3.10.2
npm install -D html-webpack-plugin clean-webpack-plugin cross-env ts-loader
新建入口js: src/main.ts
document.write('哈哈哈')
新建public/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</title>
</head>
<body>
</body>
</html>
生成 tsconfig.json
先全局安装typescript npm install -g typescript
tsc --init
如果出现 因为在此系统上禁止运行脚本 的情况 可以以管理员身份运行Windows PowerShell 使用 get-executionpolicy 查看脚本执行策略
再执行指令 set-executionpolicy RemoteSigned 就可以tsc --init了
新建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: isProd ? 'cheap-module-source-map' : 'cheap-module-eval-source-map',
devServer: {
host: 'localhost', // 主机名
stats: 'errors-only', // 打包日志输出输出错误信息
port: 8081, // 端口名
open: true, // 是否自动在默认浏览器内打开localhost:8081
},
}
配置命令行
// 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"
},