1、安装项目需要使用的npm包
yarn add webpack-merge cross-env //cross-env设置打包env
2、在项目根目录下新建build文件夹,里面新建三个webpack.config.js配置文件,分别为webpack.dev.js、webpack.prod.js、webpack.common.js
//webpack.common.js 公共模块 const HtmlWebpackPlugin = require(‘html-webpack-plugin‘) const { CleanWebpackPlugin } = require(‘clean-webpack-plugin‘) module.exports = { entry: { main: ‘./src/main.js‘ }, module: { rules: [ { test: /\.js$/, exclude: /node_modules/, loader: "babel-loader" } ] }, plugins: [ new CleanWebpackPlugin(), new HtmlWebpackPlugin({ template: ‘./src/public/index.html‘ }) ] }
//webpack.prod.js 生产模式配置 const { merge } = require(‘webpack-merge‘); const ComConfig = require(‘./webpack.common‘); const prodConfig = { mode: ‘development‘, devtool: ‘cheap-module-source-map‘ } module.exports = merge(prodConfig, ComConfig)
//webpack.dev.js 开发模式配置 const { merge } = require(‘webpack-merge‘); const ComConfig = require(‘./webpack.common‘); const path = require(‘path‘) const devConfig = { mode: ‘development‘, devtool: ‘eval-cheap-module-source-map‘, devServer: { contentBase: path.join(__dirname, "dist"), compress: true, port: 9000, open: true, }, optimization: { usedExports: true } } module.exports = merge(devConfig, ComConfig)
3、在项目根目录下的webpack.config.js中配置如下
const developmentConfig = require(‘./build/webpack.dev‘) const productionConfig = require(‘./build/webpack.prod‘) const { merge } = require(‘webpack-merge‘); const path = require(‘path‘) let config = { output: { path: path.resolve(__dirname,‘dist‘), filename: ‘[name].js‘ } } module.exports = () => { switch (process.env.NODE_ENV) { case ‘development‘: return merge(config,developmentConfig); case ‘production‘: return merge(config,productionConfig); default: throw new Error(‘No matching configuration was found!‘); } }
//webpack分模块配置成功