生产模式的时候我们使用yarn build,使用style-loader和css-loader
开发模式的时候我们使用yarn start,使用extract插件
使用两个webpack.config.js以及webpack.config.base.js(当然也可以不用,直接写两个文件)
1.命名两个webpack.config.js
一个叫webpack.config.prod.js(生产的配置)只包含了style-loader和css-loader以及mode
一个叫webpack.config.js(默认的配置)只包含了extract插件以及mode
2.自己定义一个webpack.config.base.js(用来写上面两个共有的配置)
使用方法
1.在两个webpack.config.js中使用require引入base文件的内容,并加入到各自的配置中
2.改写build方法,使其使用我们自己定义的prod.js配置文件,下面是我们的定义的脚本
"scripts": {"test": "echo \"Error: no test specified\" && exit 1","build": "rm -r dist&&webpack --config webpack.config.prod.js",//注意这里"start": "webpack-Dev-Server"}
几个文件的具体内容
webpack.config.base.js(共同配置)
const path = require('path');const HtmlWebpackPlugin = require('html-webpack-plugin');const MiniCssExtractPlugin = require('mini-css-extract-plugin');const base = require('./webpack.config.base.js')module.exports = {entry: './src/index.js',output: {filename: '[name].[contenthash].js',path: path.resolve(__dirname, 'dist')}};
webpack.config.js(开发模式)
const path = require('path');const HtmlWebpackPlugin = require('html-webpack-plugin');const MiniCssExtractPlugin = require('mini-css-extract-plugin');const base = require('./webpack.config.base.js')module.exports = {...base,mode: 'development',plugins: [new HtmlWebpackPlugin({title: 'document',template: 'src/assets/test.html'})],module: {rules: [{test: /\.css$/i,use: ['style-loader', 'css-loader'],}]},devtool: 'inline-source-map',devServer: {contentBase: './dist', // 根目录,默认同级open: true, // 自动打开浏览器port: 8080 // 端口号}};
webpack.config.prod.js(生产模式)
const path = require('path');const HtmlWebpackPlugin = require('html-webpack-plugin');const MiniCssExtractPlugin = require('mini-css-extract-plugin');const base = require('./webpack.config.base.js')module.exports = {...base,mode: 'production',plugins: [new HtmlWebpackPlugin({title: 'lalala',template: 'src/assets/test.html'}),new MiniCssExtractPlugin({filename: '[name].[contenthash].css'})],module: {rules: [{test: /\.css$/i,use: [MiniCssExtractPlugin.loader, 'css-loader'],}]}};
