记录webpack2升级至webpack4

记录webpack2升级至webpack4

1、更新webpack下载webpack-cli

node版本要6以上
npm install webpack@4 -D
npm install webpack-cli@3 -D

下面这种报错就是插件版本问题
TypeError: Cannot read property 'xxx' of undefined
"webpack": "^4.44.2",
"webpack-cli": "^3.3.12",

警告暂时没有解决

(node:43802) DeprecationWarning: Tapable.plugin is deprecated. Use new API on `.hooks` instead

2.启动报错html-webpack-plugin

在这里插入图片描述
html-webpack-plugin版本低更新版本。
npm install html-webpack-plugin@4 -D

"html-webpack-plugin": "^4.5.0",

3.启动报错babel-loader

在这里插入图片描述
babel-loader版本低更新版本
npm install babel-loader -D

"babel-loader": "^7.1.5"

4.启动报错

在这里插入图片描述
根据提示npm install --save vue

5.启动报错 vue-template-compiler

在这里插入图片描述

vue-template-compiler版本低更新版本
npm install vue-template-compiler -save

"vue-template-compiler": "^2.6.11"

6.启动报错 vue-loader

在这里插入图片描述
vue-loader版本低更新版本
npm install vue-loader@15 -D

"vue-loader": "^15.9.6"

在这里插入图片描述
根据vue官网提示vue-loader15版本的声明方法,定义plugin


// webpack.config.js
const VueLoaderPlugin = require('vue-loader/lib/plugin')

module.exports = {
  module: {
    rules: [
      // ... 其它规则
      {
        test: /\.vue$/,
        loader: 'vue-loader'
      }
    ]
  },
  plugins: [
    // 请确保引入这个插件!
    new VueLoaderPlugin()
  ]
}

15版本升级后需要改动比较多所以我升级到14版本

"vue-loader": "^14.2.4"

7.启动报错 vue-style-loader file-loader url-loader sass-loader postcss-loader

在这里插入图片描述在这里插入图片描述
版本太低更新版本
npm install vue-style-loader@4.1.2 -D
npm install url-loader@1.0.1 -D
npm install file-loader@1.1.11 -D
npm install sass-loader@7 -D
npm install postcss-loader@2.0.9 -D

"vue-style-loader": "4.1.2",
"url-loader": "1.0.1",
"file-loader": "1.1.11",
"postcss-loader": "^2.0.9",
"sass-loader": "^7.3.1",

8.注释掉删掉不推荐的插件

webpack迁移链接
在这里插入图片描述
在这里插入图片描述
全局搜索注释掉需要删除的内容我这里只删除一个需要删除内容根据webpack提示来删除
在这里插入图片描述

9.修改配置文件

webpack.optimize.UglifyJsPlugin
我的splitCunks配置

styles是解决升级后生成css文件过多的问题styles是把生成css合并成一个css文件
elementUI过大所有提前提出来单独打包
/[\\/]node_modules[\\/]/就是node_modules这个第三方库目录
[\\/]是正则里面的转义,就是/的意思
正则里面为了和系统符号区分,一般符号要做转义。\.就是.的意思
\.css就是.css的意思
后面加上$表示所有以.css结尾的文件
test后面的是规则

在这里插入图片描述

  optimization: {
    splitChunks: {
      chunks: 'all',
      cacheGroups: {
        common: {
          test: /[\\/]node_modules[\\/]/,
          name: 'vendors-common',
          minSize: 0,
          minChunks: 2, // 最少被2个chunk引用
          chunks: 'initial',
          priority: 10, // 优先级,默认是0,可以为负数
        },
        //打包多个css合并css
        styles: {
          name: 'styles',
          test: m => m.constructor.name === 'CssModule',
          chunks: 'all',
          minChunks: 1,
          enforce: true
        },
        elementUI: {
          test: /[\\/]node_modules[\\/]element-ui[\\/]/,
          name: 'chunk-elementUI', // 单独将 elementUI 拆包
          priority: 20, // 权重要大于 libs 和 app 不然会被打包进 libs 或者 app
        },
        default: {
          minChunks: 3,
          priority: -20,
          reuseExistingChunk: true
        }
      }
    },
    runtimeChunk: 'single',
    minimizer: [
      new OptimizeCSSPlugin()
    ]
  }

默认配置

来源:圣罗兰反转巴黎

/**
   * webpack中实现代码分割的两种方式:
   * 1.同步代码:只需要在webpack配置文件总做optimization的配置即可
   * 2.异步代码(import):异步代码,无需做任何配置,会自动进行代码分割,放置到新的文件中
   * 3.分离文件必须大于30kb,才可以分离成功,否则设置无效
   */
  optimization: {
    splitChunks: {
      chunks: "all",          //async对异步引入的代码分割 initial对同步引入代码分割 all对同步异步引入的分割都开启
      minSize: 30000,         //字节 引入的文件大于30kb才进行分割
      //maxSize: 50000,         //50kb,尝试将大于50kb的文件拆分成n个50kb的文件
      minChunks: 1,           //模块至少使用次数
      maxAsyncRequests: 5,    //同时加载的模块数量最多是5个,只分割出同时引入的前5个文件(按需加载模块)
      maxInitialRequests: 3,  //首页加载的时候引入的文件最多3个(加载初始页面)
      automaticNameDelimiter: '~', //缓存组和生成文件名称之间的连接符
      name: true,                  //缓存组里面的filename生效,覆盖默认命名
      cacheGroups: { //缓存组,将所有加载模块放在缓存里面一起分割打包
        vendors: {  //自定义打包模块
          test: /[\\/]node_modules[\\/]/,
          priority: -10, //优先级,先打包到哪个组里面,值越大,优先级越高
          filename: 'vendors.js',
        },
        default: { //默认打包模块
          priority: -20,
          reuseExistingChunk: true, //模块嵌套引入时,判断是否复用已经被打包的模块
          filename: 'common.js'
        }
      }
    }
  }

详细解释,作者:大勇哥~

10. ‘extract-text-webpack-plugin’改成’mini-css-extract-plugin’

全局搜索extract-text-webpack-plugin

package.json文件
"extract-text-webpack-plugin": "^2.0.0",替换为mini
"mini-css-extract-plugin": "0.4.1",

在这里插入图片描述

// var ExtractTextPlugin = require('extract-text-webpack-plugin')
const MiniCssExtractPlugin = require('mini-css-extract-plugin')


function generateLoaders(loader, loaderOptions) {
    var loaders = [cssLoader]
    if (loader) {
      loaders.push({
        loader: loader + '-loader',
        options: Object.assign({}, loaderOptions, {
          sourceMap: options.sourceMap
        })
      })
    }

    // Extract CSS when that option is specified
    // (which is the case during production build)
    if (options.extract) {
      return ExtractTextPlugin.extract({
        use: loaders,
        fallback: 'vue-style-loader'
      })
    } else {
      return ['vue-style-loader'].concat(loaders)
    }
  }
      
  //上面 ExtractTextPlugin 改成下面 MiniCssExtractPlugin
  exports.cssLoaders = function (options) {
  ...
    const postcssLoader = {
    loader: 'postcss-loader',
    options: {
      sourceMap: options.sourceMap
    }
  }
    
    function generateLoaders(loader, loaderOptions) {
    const loaders = []
    // Extract CSS when that option is specified
    // (which is the case during production build)
    if (options.extract) {
      loaders.push({
        loader: MiniCssExtractPlugin.loader,
        options: { publicPath: '../../' }
      })

    } else {
      loaders.push('vue-style-loader')
    }
    loaders.push(cssLoader)

    if (options.usePostCSS) {
      loaders.push(postcssLoader)
    }
    if (loader) {
      loaders.push({
        loader: loader + '-loader',
        options: Object.assign({}, loaderOptions, {
          sourceMap: options.sourceMap
        })
      })
    }
    return loaders
    // https://vue-loader.vuejs.org/en/configurations/extract-css.html
  }
  ...
  }
     

顺序要对

上面是封装的改法,下面这种是未封装改法(从右往左进行)
	module: {
	 	rules: [
		 	 	{
	                test: /\.css$/,
	                use: [
	                    { 
	                        loader: MiniCssExtractPlugin.loader
	                    },
	                    'css-loader'
	                ]
	            },
	         	{
		        	test: /\.(css|stylus)$/,
		        	use: [
			          	MiniCssExtractPlugin.loader,
			          	'css-loader',
			          	'stylus-loader'                                 
		        	],
		        }
		]
	}
//webpack.prod.conf页面下
// var ExtractTextPlugin = require('extract-text-webpack-plugin')
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
  plugins: [
  ...
	 new ExtractTextPlugin({
      filename: utils.assetsPath('css/[name].[contenthash].css')
    })
    
      上面 ExtractTextPlugin 改成下面 MiniCssExtractPlugin
     new MiniCssExtractPlugin({
      filename: utils.assetsPath('css/[name].[contenthash].css')
    }),
  ...
   ]
     

11. 修改build下dev-server文件 compiler.plugin弃用

dev-server.js
var HtmlWebpackPlugin = require('html-webpack-plugin')

//force page reload when html-webpack-plugin template changes
compiler.plugin('compilation', function (compilation) {
  compilation.plugin('html-webpack-plugin-after-emit', function (data, cb) {
    hotMiddleware.publish({ action: 'reload' })
    cb()
  })
})
//修改为
compiler.hooks.compilation.tap('MyPlugin', (compilation) => {
  HtmlWebpackPlugin.getHooks(compilation).afterEmit.tapAsync(
    'MyPlugin', (data, cd) => {
      hotMiddleware.publish({ action: 'reload' })
      cd()
    })
})

12. 报错dependency

chunksSortMode: 'dependency’

    new HtmlWebpackPlugin({
    ...
    //注释掉 chunksSortMode: 'dependency'
    // chunksSortMode: 'dependency'
    ...

13. 使用HappyPack提升项目构建速度

loader 替换为 happypack/loaderid对应plugins里HappyPack的 id

   	// 引用HappyPack
   	 const HappyPack = require('happypack')
   	//构造出一个共享进程池,在进程池中包含4个子进程
   	const happyThreadPool = HappyPack.ThreadPool({
   	  size: 4//同时加载数
   	})
   	module: {
   		rules: [
   			...
   			 {
   		        test: /\.js$/,
   		        loader: "babel-loader",
   		 		...
   		      },
   		     // 修改为
   			{
   		        test: /\.js$/,
   		        loader: 'happypack/loader?id=babel',
   		     	...
    			},
   			...
   		]
   	}
   	  plugins: [new HappyPack({
   	    // 用唯一的标识符 id 来代表当前的 HappyPack 是用来处理一类特定的文件
   	    id: 'babel',
   	    // 如何处理 .js 文件,用法和 Loader 配置中一样
   	    loaders: ['babel-loader?cacheDirectory=true'],
   	    //使用共享进程池中的自进程去处理任务
   	    threadPool: happyThreadPool,
   	    //是否允许happypack输出日志,默认true
   	    verbose: true
   	  }),new HappyPack({
   	   ·····
   	  }),
   	  ]
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值