1、安装项目需要使用的npm包
yarn add webpack-merge cross-env html-webpack-plugin clean-webpack-plugin babel-loader @babel/core //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') const path=require('path') module.exports = { entry: { main: './src/main.js' }, module: { rules: [ { test: /\.js$/, exclude: /node_modules/, //exclude 表示不用babel-loader 处理node_modules中的文件,外部引入的文件一般都处理过 loader: "babel-loader" } ] }, plugins: [ new CleanWebpackPlugin(), new HtmlWebpackPlugin({ template: './src/public/index.html' }) ], output: { path: path.join(__dirname,'..', 'dist'), filename: '[name].js' } }
//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: 'production', 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、在项目根目录下的package.json中配置
"scripts": { "build": "cross-env NODE_ENV=production webpack --config ./build/webpack.prod.js", "start": "cross-env NODE_ENV=development webpack-dev-server --config ./build/webpack/dev.js" },
4、webpack分模块配置成功