webpack3.x升级到webpack4.x

妖狐艹你老母 2022-12-21 06:08 570阅读 0赞

虽然说webpack5都已经出了,但是,可能有一部分人还在用webpack3,因此这篇文章主要是基于vue-cli中到项目配置,从webpack3升级到4.x。

由于webpack3升级到4以后,很多配置项发生了变化,因此在升级过程中会遇到很多坑。

  1. webpack.base.conf.js

首先。从webpack.base.conf.js开始,输入输出和上下文配置基本一样的,这边在plugin的位置引入了VueLoaderPlugin,同时把HtmlWebpackPlugin也提取到这里

  1. plugins: [
  2. new VueLoaderPlugin(),
  3. new HtmlWebpackPlugin({
  4. filename: `index.html`,
  5. template: root + '/index.html',
  6. // favicon:path.resolve('favicon.ico'),
  7. prod: true,
  8. hash: true,
  9. minify: {
  10. removeAttributeQuotes: true,
  11. collapseWhitespace: true,
  12. html5: true,
  13. minifyCSS: true,
  14. removeComments: true,
  15. removeEmptyAttributes: true
  16. }
  17. }),
  18. ]
  1. webpack.dev.conf.js

webpack4必须引入一个mode参数左右判断dev和prod的环境,

基本的一些配置信息还是相同的,下图左侧位webpack3的配置,右侧是webpack4的配置。

watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L21pY2hhZWw4NTEy_size_16_color_FFFFFF_t_70

  1. webpack.prod.conf.js(重点在这个文件)

1)webpack4取消了uglify-webpack-plugin这个插件,改用了minizer这个属性

  1. optimization: {
  2. noEmitOnErrors: true,
  3. minimizer: [
  4. // new UglifyJsPlugin({
  5. // cache: true,
  6. // parallel: true,
  7. // sourceMap: false // set to true if you want JS source maps
  8. // }),
  9. new OptimizeCssAssetsPlugin({
  10. cssProcessor: require('cssnano')
  11. })
  12. ],
  13. splitChunks: {
  14. chunks: 'all'
  15. }
  16. },

2)extract-text-webpack-plugin,CommonsChunksPlugin这个插件也不再适用

3)引入了happpyPack并行打包

  1. const ProgressBarPlugin = require('progress-bar-webpack-plugin');
  2. const merge = require('webpack-merge');
  3. const utils = require('./utils')
  4. const path = require('path')
  5. const webpackbase = require('./webpack.base.conf.js');
  6. const MiniCssExtractPlugin = require('mini-css-extract-plugin');
  7. const OptimizeCssAssetsPlugin = require('optimize-css-assets-webpack-plugin');
  8. const chalk = require('chalk');
  9. const { CleanWebpackPlugin } = require('clean-webpack-plugin');
  10. const config = require('../config');
  11. const HtmlWebpackPlugin = require('html-webpack-plugin');
  12. // const UglifyJsPlugin = require('uglifyjs-webpack-plugin');
  13. // const ParallelUglifyPlugin = require('webpack-parallel-uglify-plugin');
  14. const _version = new Date().getTime();
  15. const HtmlWebpackTagsPlugin = require('html-webpack-tags-plugin');
  16. const dllHelper = require('../config/dllHelper');
  17. const CopyWebpackPlugin = require('copy-webpack-plugin')
  18. const OptimizeCSSPlugin = require('optimize-css-assets-webpack-plugin')
  19. const HappyPack = require('happypack');
  20. const webpackProdConfig = {
  21. devtool: 'inline-cheap-source-map',
  22. mode: 'production',
  23. output: {
  24. path: config.build.assetsRoot,
  25. filename: '[name].js',
  26. publicPath: './'
  27. },
  28. optimization: {
  29. noEmitOnErrors: true,
  30. minimizer: [
  31. // new UglifyJsPlugin({
  32. // cache: true,
  33. // parallel: true,
  34. // sourceMap: false // set to true if you want JS source maps
  35. // }),
  36. new OptimizeCssAssetsPlugin({
  37. cssProcessor: require('cssnano')
  38. })
  39. ],
  40. splitChunks: {
  41. chunks: 'all'
  42. }
  43. },
  44. plugins: [
  45. new CleanWebpackPlugin(),
  46. // new ExtractTextPlugin({
  47. // filename: utils.assetsPath('css/[name].[contenthash].css'),
  48. // allChunks: true,
  49. // }),
  50. new OptimizeCSSPlugin({
  51. cssProcessorOptions: true
  52. ? { safe: true, map: { inline: false } }
  53. : { safe: true }
  54. }),
  55. new CopyWebpackPlugin([
  56. {
  57. from: path.resolve(__dirname, '../static'),
  58. to: 'static',
  59. ignore: ['.*']
  60. }
  61. ]),
  62. ...dllHelper.genDllReferences(),
  63. new HappyPack({
  64. id: 'js',
  65. use: [
  66. {
  67. test: /\.js$/,
  68. loader: 'babel-loader',
  69. },
  70. ]
  71. }),
  72. new HtmlWebpackTagsPlugin({
  73. assets: dllHelper.loadDllAssets(),
  74. append: false
  75. }),
  76. new HtmlWebpackPlugin({
  77. filename: process.env.NODE_ENV === 'testing'
  78. ? 'index.html'
  79. : config.build.index,
  80. template: 'index.html',
  81. // favicon:path.resolve('favicon.ico'),
  82. prod: true,
  83. hash: true,
  84. minify: {
  85. removeAttributeQuotes: true,
  86. collapseWhitespace: true,
  87. html5: true,
  88. minifyCSS: true,
  89. removeComments: true,
  90. removeEmptyAttributes: true
  91. }
  92. }),
  93. new MiniCssExtractPlugin({
  94. filename: utils.assetsPath(`css/[name].${_version}.css`),
  95. chunkFilename: utils.assetsPath(`css/[name].${_version}.css`),
  96. }),
  97. new ProgressBarPlugin(
  98. {
  99. format: chalk.blueBright(' build :bar :percent (:elapsed seconds) '),
  100. clear: false,
  101. summary: false,
  102. customSummary: res => {
  103. process.stderr.write(chalk.blueBright.bold(` build end use time ${res} \n`))
  104. }
  105. }
  106. ),
  107. // new ParallelUglifyPlugin({
  108. // uglifyJS: {
  109. // output: {
  110. // beautify: false,
  111. // comments: false
  112. // },
  113. // compress: {
  114. // drop_console: true,
  115. // collapse_vars: true,
  116. // reduce_vars: true
  117. // }
  118. // }
  119. // })
  120. ]
  121. }
  122. // if (config.build.productionGzip) {
  123. // const CompressionWebpackPlugin = require('compression-webpack-plugin')
  124. // webpackProdConfig.plugins.push(
  125. // new CompressionWebpackPlugin({
  126. // filename: '[path].gz[query]',
  127. // algorithm: 'gzip',
  128. // test: new RegExp(
  129. // '\\.(' +
  130. // config.build.productionGzipExtensions.join('|') +
  131. // ')$'
  132. // ),
  133. // threshold: 10240,
  134. // minRatio: 0.8
  135. // })
  136. // )
  137. // }
  138. if (config.build.bundleAnalyzerReport) {
  139. const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin
  140. webpackProdConfig.plugins.push(new BundleAnalyzerPlugin())
  141. }
  142. module.exports = merge(webpackbase, webpackProdConfig)

4)引入了webpack.dll.conf.js用于提升打包速度

  1. const path = require('path')
  2. const webpack = require('webpack');
  3. const merge = require('webpack-merge')
  4. const ExtractTextPlugin = require('extract-text-webpack-plugin');
  5. const {CleanWebpackPlugin} = require("clean-webpack-plugin")
  6. const OptimizeCssAssetsPlugin = require('optimize-css-assets-webpack-plugin');
  7. const utils = require('./utils')
  8. const dllConfig = {
  9. mode: 'production',
  10. context: path.resolve(__dirname, '../'),
  11. output: {
  12. path: path.join(__dirname, '../static/lib'),
  13. filename: '[name]_[hash:4].dll.js',
  14. library: '[name]_[hash:4]'
  15. },
  16. entry: {
  17. lib: [
  18. 'axios',
  19. 'moment',
  20. ],
  21. vue: [
  22. 'vue/dist/vue.js',
  23. 'vue-router',
  24. ],
  25. },
  26. // optimization: {
  27. // noEmitOnErrors: true,
  28. // minimizer: [
  29. // new OptimizeCssAssetsPlugin({
  30. // cssProcessor: require('cssnano')
  31. // })
  32. // ],
  33. // splitChunks: {
  34. // chunks: 'all'
  35. // }
  36. // },
  37. module: {
  38. rules: [{
  39. test: /\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/,
  40. loader: "url-loader?limit=10000&mimetype=application/font-woff",
  41. options: {
  42. name: utils.assetsPath('fonts/[name].[ext]')
  43. }
  44. }, {
  45. test: /\.(ttf|eot|svg)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
  46. loader: "file-loader",
  47. options: {
  48. name: utils.assetsPath('fonts/[name].[ext]')
  49. }
  50. }]
  51. },
  52. plugins: [
  53. new CleanWebpackPlugin(),
  54. new webpack.DllPlugin({
  55. context: __dirname,
  56. path: path.join(__dirname, '../static/dll', '[name].manifest.json'),
  57. name: '_dll_[name]_[hash]',
  58. }),
  59. new webpack.ProvidePlugin({
  60. '$': 'jquery',
  61. 'jQuery': 'jquery',
  62. 'window.jQuery': 'jquery',
  63. 'window.$': 'jquery',
  64. }),
  65. new ExtractTextPlugin('[name].css'),
  66. ],
  67. performance: {
  68. hints: "warning", // 枚举
  69. maxAssetSize: 30000000, // 整数类型(以字节为单位)
  70. maxEntrypointSize: 50000000, // 整数类型(以字节为单位)
  71. assetFilter: function(assetFilename) {
  72. // 提供资源文件名的断言函数
  73. return assetFilename.endsWith('.css') || assetFilename.endsWith('.js');
  74. }
  75. }
  76. }
  77. module.exports = merge(dllConfig, {
  78. module: {
  79. rules: utils.styleLoaders({
  80. sourceMap: true,
  81. extract: true,
  82. usePostCSS: true
  83. })
  84. }
  85. });

小结:详细的工程参考下面github地址

文章写的比较简介,最好自己从头到尾配置一遍,这样印象比较深刻

https://github.com/michael8512/vue2x-webpack4

发表评论

表情:
评论列表 (有 0 条评论,570人围观)

还没有评论,来说两句吧...

相关阅读

    相关 webpack4.x 第二节

    webpack4.x 打包初体验 在根目录下建一个src(源码)目录 在建一个dist(打包后)目录 在src下建一个入口文件,index.js // in