多配置文件

可以使用多个配置文件,把相同的配置项放在一个通用配置文件中,再为开发环境和生产环境写一个基于通用配置的配置文件。打包时加上 config 参数 —— “— config 文件名” 来指定使用的配置文件。

  1. // 通用配置文件
  2. // webpack.common.js
  3. const HtmlWebpackPlugin = require('html-webpack-plugin')
  4. module.exports = {
  5. entry: './src/main.js',
  6. output: {
  7. filename: 'js/bundle.js'
  8. },
  9. module: {
  10. rules: [
  11. {
  12. test: /\.css$/,
  13. use: [
  14. 'style-loader',
  15. 'css-loader'
  16. ]
  17. },
  18. {
  19. test: /\.(png|jpe?g|gif)$/,
  20. use: {
  21. loader: 'file-loader',
  22. options: {
  23. outputPath: 'img',
  24. name: '[name].[ext]'
  25. }
  26. }
  27. }
  28. ]
  29. },
  30. plugins: [
  31. new HtmlWebpackPlugin({
  32. title: 'Webpack Tutorial',
  33. template: './src/index.html'
  34. })
  35. ]
  36. }
  1. // 开发环境配置文件
  2. // webpack.dev.js
  3. const webpack = require('webpack')
  4. const merge = require('webpack-merge')
  5. const common = require('./webpack.common')
  6. module.exports = merge(common, {
  7. mode: 'development',
  8. devtool: 'cheap-eval-module-source-map',
  9. devServer: {
  10. hot: true,
  11. contentBase: 'public'
  12. },
  13. plugins: [
  14. new webpack.HotModuleReplacementPlugin()
  15. ]
  16. })
  1. // 生产环境配置文件
  2. // webpack.prod.js
  3. const merge = require('webpack-merge')
  4. const { CleanWebpackPlugin } = require('clean-webpack-plugin')
  5. const CopyWebpackPlugin = require('copy-webpack-plugin')
  6. const common = require('./webpack.common')
  7. module.exports = merge(common, {
  8. mode: 'production',
  9. plugins: [
  10. new CleanWebpackPlugin(),
  11. new CopyWebpackPlugin(['public'])
  12. ]
  13. })

单配置文件

在配置文件中判断打包环境,适用于中小型项目。

  1. module.exports = (env, argv) => {
  2. const config = {
  3. // 通用配置
  4. }
  5. if (env === 'production') {
  6. config.mode = 'production'
  7. config.devtool = false
  8. config.plugins = [
  9. ...config.plugins,
  10. new CleanWebpackPlugin(),
  11. new CopyWebpackPlugin(['public'])
  12. ]
  13. }
  14. return config
  15. }