npm init -y
命令来初始化当前文件夹下的package.json文件。
- npm install --save typescript
- npm install --save webpack@4.41.5 webpack-cli@3.3.10 webpack-dev-server@3.10.2
- npm install --save html-webpack-plugin@4.4.1 clean-webpack-plugin
- npm install --save ts-loader@4.0.0 cross-env
注意:
- 当执行
npm run dev
报如下错误TypeError: Cannot read property 'tap' of undefined at HtmlWebpackPlugin.apply (F:\typescript_study\01_Typescript\03.webpack_ts\node_modules\html-webpack-plugin\index.js:40:31)
说明html-webpack-plugin的版本和webpack的版本不匹配,此时要确保webpack和html-webpack-plugin版本一致。比如webpack4使用h-w-p4.,webpack5使用h-w-h5.- 当执行
npm run dev
报如下错误Module build failed (from ./node_modules/ts-loader/index.js): TypeError: loaderContext.getOptions is not a function
这个时候就需要把ts-loader这个模块的版本号和对应的webpack的版本号保持一致就可以解决问题了。
src/main.js
public/index.html
build/webpack.config.js文件
// clean-webpack-plugin这个插件会在打包前删除原来打包的文件
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
// html-webpack-plugin这个插件会帮助我们在 webpack 打包结束后,自动生成一个 html 文件,并把打包产生文件引入到这个 html 文件中去。
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' // 指定以这个目录下的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
},
}
"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"
npm run dev
执行webpack-dev-server,执行npm run build
进行webpack打包