实战笔记:Vue2项目Webpack 3升级到Webpack 4的实操指南

打印 上一主题 下一主题

主题 922|帖子 922|积分 2766

在Web开发领域,保持技术的更新好坏常重要的。随着前端构建工具的快速发展,Webpack已经更新到5.x版本,如果你正在利用Vue2项目,并且还在利用Webpack 3,那么是时候考虑升级一下Webpack了。我最近将我的Vue2项目从Webpack 3升级到了Webpack 4。以下是我升级过程中积累的履历和步调,希望能帮助那些准备进行雷同升级的开发者。
写在前面

为什么不直接升级到webpack5.x?

这个问题问得很好,我最开始也是直接一键升级到最新版,一启动,直接报各种版本不匹配(哭),由于项目比较大引入的依赖太多,实在是难以推进,所以退而求其次,先升级到webpack4.x,后面再想办法往上升!!!
升级前的准备

在进行任何庞大的项目改动之前,备份总是第一位的。请首先确保你的项目已经被推送到Git仓库,如许纵然升级失败,也能轻松回退到之前的版本。
升级开始

我本来的webpack版本是^3.6.0,本次升级为:^4.46.0
我本次升级涉及到的文件目次如下:

1、更新package.json中Webpack和相关依赖 

以下是我本次升级新增以及更新的依赖版本:
依赖原版本升级后版本范例
babel-polyfill     --^6.26.0新增
babel-plugin-transform-es2015-modules-commonjs--^6.26.2新增
html-webpack-plugin^2.30.1^4.3.0升级
mini-css-extract-plugin--0.9.0新增
vue-loader^13.3.0^15.7.0升级
webpack^3.6.0^4.46.0升级
webpack-cli--3.3.12新增
webpack-dev-server^2.11.5^3.11.1升级
2、安装依赖

  1. npm install
复制代码
如果由于项目中其他依赖冲突产生的报错及安装失败,可以加上--legacy-peer-deps
 
  1. npm install --legacy-peer-deps
复制代码
3、 逐步修改Webpack设置

.babelrc文件:

  1. // 修改前
  2. {
  3.   "presets": [
  4.     ["env", {
  5.       "modules": false,
  6.       "targets": {
  7.         "browsers": ["> 1%", "last 2 versions", "not ie <= 8"]
  8.       }
  9.     }],
  10.     "stage-2"
  11.   ],
  12.   "plugins": ["transform-vue-jsx", "transform-runtime"]
  13. }
  14. // 修改后
  15. {
  16.   "presets": [
  17.     ["env", {
  18.       "modules": false,
  19.       "targets": {
  20.         "browsers": ["> 1%", "last 2 versions", "not ie <= 8"]
  21.       }
  22.     }],
  23.     "stage-2"
  24.   ],
  25.   "plugins": ["transform-vue-jsx", "transform-runtime","transform-es2015-modules-commonjs"]
  26. }
复制代码
build/utils.js文件:

  1. // 删除或注释以下代码
  2. const ExtractTextPlugin = require('extract-text-webpack-plugin')
  3. // 改为
  4. const MiniCssExtractPlugin = require('mini-css-extract-plugin')
  5. // 删除或注释以下代码
  6.   if (options.extract) {
  7.       return ExtractTextPlugin.extract({
  8.         use: loaders,
  9.         fallback: 'vue-style-loader',
  10.         // https://www.cnblogs.com/luosiding/p/8268837.html
  11.         publicPath: '../../'
  12.       })
  13.     } else {
  14.       return ['vue-style-loader'].concat(loaders)
  15.     }
  16. // 改为
  17. return [options.extract ? MiniCssExtractPlugin.loader : 'vue-style-loader'].concat(loaders)
复制代码
build/webpack.base.conf.js文件:

  1. // 删除或注释以下代码
  2. const vueLoaderConfig = require('./vue-loader.conf')
  3. // 改为
  4. const { VueLoaderPlugin } = require('vue-loader')
  5. // module.exports中:
  6. entry: {
  7.     app: './src/main.js'
  8.   },
  9. // 改为:
  10. entry: {
  11.     app: ['babel-polyfill', './src/main.js']
  12.   },
  13. // 新增:
  14. mode:process.env.NODE_ENV,
  15. plugins: [
  16.     new VueLoaderPlugin()
  17.   ],
  18. // 删掉options
  19.   module: {
  20.     rules: [
  21.       //...(config.dev.useEslint ? [createLintingRule()] : []),
  22.       {
  23.         test: /\.vue$/,
  24.         loader: 'vue-loader',
  25.         options: vueLoaderConfig //删除该条
  26.       },
复制代码
 build/webpack.dev.conf.js文件:

如果项目中利用了jquery才改:
  1. plugins: [
  2. ...,
  3. new webpack.ProvidePlugin({
  4.       $: 'jquery'
  5.     })
  6. ]
复制代码
  build/webpack.prod.conf.js文件:

  1. // 删掉或注释以下代码
  2. const ExtractTextPlugin = require('extract-text-webpack-plugin')
  3. // 改为
  4. const MiniCssExtractPlugin = require('mini-css-extract-plugin')
  5. // 删掉或注释以下代码
  6. new UglifyJsPlugin({
  7.       uglifyOptions: {
  8.         compress: {
  9.           warnings: false
  10.         }
  11.       },
  12.       sourceMap: config.build.productionSourceMap,
  13.       parallel: true
  14.     }),
  15. new ExtractTextPlugin({
  16.       filename: utils.assetsPath('css/[name].[contenthash].css'),
  17.       // Setting the following option to `false` will not extract CSS from codesplit chunks.
  18.       // Their CSS will instead be inserted dynamically with style-loader when the codesplit chunk has been loaded by webpack.
  19.       // It's currently set to `true` because we are seeing that sourcemaps are included in the codesplit bundle as well when it's `false`,
  20.       // increasing file size: https://github.com/vuejs-templates/webpack/issues/1110
  21.       allChunks: true,
  22.     }),
  23. // 改为:
  24. new MiniCssExtractPlugin({
  25.       filename: utils.assetsPath('css/[name].[contenthash].css'),
  26.       ignoreOrder: true
  27.     }),
  28. // 删掉或注释以下代码:
  29. chunksSortMode: 'dependency'
  30. // 改为:
  31. chunksSortMode: 'none'
  32. // 删掉或注释以下代码:
  33.     new webpack.optimize.CommonsChunkPlugin({
  34.       name: 'vendor',
  35.       minChunks (module) {
  36.         // any required modules inside node_modules are extracted to vendor
  37.         return (
  38.           module.resource &&
  39.           /\.js$/.test(module.resource) &&
  40.           module.resource.indexOf(
  41.             path.join(__dirname, '../node_modules')
  42.           ) === 0
  43.         )
  44.       }
  45.     }),
  46.     // extract webpack runtime and module manifest to its own file in order to
  47.     // prevent vendor hash from being updated whenever app bundle is updated
  48.     new webpack.optimize.CommonsChunkPlugin({
  49.       name: 'manifest',
  50.       minChunks: Infinity
  51.     }),
  52.     // This instance extracts shared chunks from code splitted chunks and bundles them
  53.     // in a separate chunk, similar to the vendor chunk
  54.     // see: https://webpack.js.org/plugins/commons-chunk-plugin/#extra-async-commons-chunk
  55.     new webpack.optimize.CommonsChunkPlugin({
  56.       name: 'app',
  57.       async: 'vendor-async',
  58.       children: true,
  59.       minChunks: 3
  60.     }),
  61. // 改为:
  62. optimization: {
  63.     minimizer: [
  64.       new UglifyJsPlugin({
  65.         parallel: true, // 开启多进程压缩。
  66.         uglifyOptions: {
  67.           output: { comments: false },
  68.           compress: {
  69.             warnings: false,
  70.             drop_debugger: true, // 是否清除debugger
  71.             drop_console: true // 是否清除所有console
  72.             // pure_funcs: ['console.log','console.info','console.warn','console.debug']     
  73.             //drop_console 设置false,需要特殊清除的
  74.           }
  75.         },
  76.         sourceMap: config.build.productionSourceMap
  77.       })
  78.     ],
  79.     splitChunks: {
  80.       chunks: 'async',
  81.       minSize: 30000, // 大于30KB才单独分离成chunk
  82.       maxAsyncRequests: 5,
  83.       maxInitialRequests: 3,
  84.       name: true,
  85.       cacheGroups: {
  86.         default: {
  87.           priority: -20,
  88.           reuseExistingChunk: true
  89.         },
  90.         // 生成 vendors.js,
  91.         vendors: {
  92.           name: 'vendors',
  93.           test: /[\\/]node_modules[\\/]/,
  94.           priority: 10,
  95.           chunks: 'all'
  96.           // enforce: true
  97.         },
  98.         common: {
  99.           name: 'common',
  100.           chunks: 'all',
  101.           minChunks: 2,
  102.           minSize: 0,
  103.           maxInitialRequests: 5 // The default limit is too small to showcase the effect
  104.         }
  105.       }
  106.     },
  107.     // 生成 manifest.js
  108.     runtimeChunk: {
  109.       name: 'manifest'
  110.     }
  111.   }
复制代码
总结 

如果改完可以正常启动,那么恭喜你!升级成功了!!如果不幸失败了,那么。。。很歉仄没有给你提供有效的帮助(哭),你也可以留言或私信,我看看有没有遇到雷同报错。希望我的履历能帮助你在升级Vue2项目到Webpack 4的过程中少走弯路!



免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

卖不甜枣

金牌会员
这个人很懒什么都没写!

标签云

快速回复 返回顶部 返回列表