步骤:
- 安装webpack、webpack-cli、webpack-dev-server、html-webpack-plugin
yarn add webpack webpack-cli webpack-dev-server html-webpack-plugin
- webpack.config.js配置plugins
const path = require('path')
const webpack = require('webpack')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const env = process.env.NODE_ENV
const isDev = process.env.NODE_ENV === 'development'
// console.log(process.env)
const config = {
target: 'web',
entry: ['./main.js'],
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'bundle.js'
},
mode: env,
plugins: [
new HtmlWebpackPlugin({
filename: 'index.html',
template: 'index.html',
inject: true
})
]
}
if (isDev) {
config.devServer = {
port: 9000,
host: 'localhost',
overlay: {
errors: true
},
open: true,
hot: true
}
// 添加热更新模块
config.plugins.push(
new webpack.DefinePlugin({
'process.evn': '"development"' //添加全局变量
}),
new webpack.HotModuleReplacementPlugin(),
new webpack.NoEmitOnErrorsPlugin()
)
config.devtool = '#cheap-module-eval-source-map'
}
module.exports = config
- package.json文件命令调用
"scripts": {
"dev": "webpack-dev-server --config webpack.config.js"
},
网友评论