生产模式的时候我们使用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配置文件,下面是我们的定义的脚本

  1. "scripts": {
  2. "test": "echo \"Error: no test specified\" && exit 1",
  3. "build": "rm -r dist&&webpack --config webpack.config.prod.js",//注意这里
  4. "start": "webpack-Dev-Server"
  5. }

几个文件的具体内容

webpack.config.base.js(共同配置)

  1. const path = require('path');
  2. const HtmlWebpackPlugin = require('html-webpack-plugin');
  3. const MiniCssExtractPlugin = require('mini-css-extract-plugin');
  4. const base = require('./webpack.config.base.js')
  5. module.exports = {
  6. entry: './src/index.js',
  7. output: {
  8. filename: '[name].[contenthash].js',
  9. path: path.resolve(__dirname, 'dist')
  10. }
  11. };

webpack.config.js(开发模式)

  1. const path = require('path');
  2. const HtmlWebpackPlugin = require('html-webpack-plugin');
  3. const MiniCssExtractPlugin = require('mini-css-extract-plugin');
  4. const base = require('./webpack.config.base.js')
  5. module.exports = {
  6. ...base,
  7. mode: 'development',
  8. plugins: [new HtmlWebpackPlugin({
  9. title: 'document',
  10. template: 'src/assets/test.html'
  11. })],
  12. module: {
  13. rules: [
  14. {
  15. test: /\.css$/i,
  16. use: ['style-loader', 'css-loader'],
  17. }
  18. ]
  19. },
  20. devtool: 'inline-source-map',
  21. devServer: {
  22. contentBase: './dist', // 根目录,默认同级
  23. open: true, // 自动打开浏览器
  24. port: 8080 // 端口号
  25. }
  26. };

webpack.config.prod.js(生产模式)

  1. const path = require('path');
  2. const HtmlWebpackPlugin = require('html-webpack-plugin');
  3. const MiniCssExtractPlugin = require('mini-css-extract-plugin');
  4. const base = require('./webpack.config.base.js')
  5. module.exports = {
  6. ...base,
  7. mode: 'production',
  8. plugins: [new HtmlWebpackPlugin({
  9. title: 'lalala',
  10. template: 'src/assets/test.html'
  11. }),
  12. new MiniCssExtractPlugin({
  13. filename: '[name].[contenthash].css'
  14. })]
  15. ,
  16. module: {
  17. rules: [
  18. {
  19. test: /\.css$/i,
  20. use: [MiniCssExtractPlugin.loader, 'css-loader'],
  21. }
  22. ]
  23. }
  24. };

另一种方法(使用别人写好的代码,webpack-merge插件)

还没有仔细研究过
https://github.com/survivejs/webpack-merge