vue2项目从webpack3升级到webpack4过程全记录以及多页面打包

升级各种插件,尤其是babel系列,从6升级到了7

  1. babel7系列的安装大多是@babel/开头,至少需要安装以下插件
	"@babel/core": "^7.4.5", //核心包
    "@babel/plugin-syntax-dynamic-import": "^7.2.0",
    "@babel/plugin-transform-runtime": "^7.4.4",
    "@babel/preset-env": "^7.4.5", //
    "@vue/babel-plugin-transform-vue-jsx": "^1.0.0",
    //dependencies
    "@babel/runtime": "^7.5.5",
    "@babel/runtime-corejs2": "^7.5.5",
  1. .babelrc文件配置修改为如下:
    不再有stage-*的配置
{
  "presets": [
    [
      "@babel/preset-env", {
        "useBuiltIns": "usage",
        "modules": false,
        "targets": {
          "browsers": ["> 1%", "last 2 versions", "not ie <= 8"]
        },
		"corejs": 3
      }
    ]
  ],
  "plugins": [
    ["@babel/plugin-syntax-dynamic-import"],
    ["@babel/plugin-transform-runtime"],
    ["@vue/babel-plugin-transform-vue-jsx"],
	[
  ]
}

webpack3升级到webpack4需要修改的配置

  1. webpack4 新增mode属性,用于指定是否是开发环境,(生产环境会默认压缩代码)
    {
    mode: ‘production’
    }
  2. css等样式处理
    webpack3打包提取单独的css文件用的extract-text-webpack-plugin插件已废弃,改用mini-css-extract-plugin

使用方法如下:

{
	plugins:[
		new MiniCssExtractPlugin({
	      filename: utils.assetsPath('css/[name].[contenthash].css'),
	      allChunks: true,
	    }),
	]
}
  1. 处理样式的loader
    开发环境依然是通过css-loader等处理后最后由vue-style-loader

生产环境需要css-loader等处理后最后用mini-css-extract-plugin自带的loader

{
	test: /\.(scss|sass)$/,
	use: [
		{
			loader: MiniCssExtractPlugin.loader,
			options: Object.assign({}, {
				publicPath: '../'
			})
		},
		{
			loader: 'css-loader',
			options: cssOptions
		},
		{
			loader: 'postcss-loader',
			options: {
				ident: 'postcss',
				plugins: () => [
					require('postcss-flexbugs-fixes'),
				],
			sourceMap: config.build.productionSourceMap,
		},
		{
			loader: 'sass-loader',
		}
	]
	// exclude: /node_modules/,
	sideEffects: true
},

  1. split代码
    webpack3采用的是webpack.optimize.CommonsChunkPlugin提取公共代码
    webpack4弃用该插件,在optimization属性里通过splitChunks属性来提取
{
	optimization: {
		splitChunks: {
      	chunks: 'async',
      	minSize: 30000,
      	maxAsyncRequests: 5,
      	maxInitialRequests: 3,
      	name: true,
	    cacheGroups: {
	        vendor: {
	          name: 'vendor',
	          test: /node_modules[\\/]/,
	          chunks: 'all',
	        //   priority: -10,
	        },
	        commons: {
	          name: "app",
	          chunks: "initial",
	          minChunks: 2,
	        },
	      }
   	 	}
	}
}
  1. webpack.optimize.UglifyJsPlugin插件也失效了,可以在optimization的minimizer属性里配置压缩方法,或者在plugins里配置压缩插件
//压缩js和css
const OptimizeCSSPlugin = require('optimize-css-assets-webpack-plugin')
const UglifyJsPlugin = require('uglifyjs-webpack-plugin')

{
	optinization: {
		minimizer: [
	      new OptimizeCSSPlugin({
	        cssProcessorOptions: config.build.productionSourceMap ? {
	          safe: true,
	          map: {
	            inline: false
	          }
	        } : {
	          safe: true
	        }
	      }),
	
	    ],
	}
}

或者minimizer设为true,(当mode是production是,默认是true)采用默认的压缩方法

vue-loader

vue-loader升级到15以上以后,使用时需要在plugins里新增一个配置项

const VueLoaderPlugin = require(‘vue-loader/lib/plugin’)

new VueLoaderPlugin(),

html-webpack-plugin

以上配置都修改之后,运行打包时遇到报错
UnhandledPromiseRejectionWarning: Error: Cyclic dependency
修改配置属性: chunksSortMode: ‘none’ ;

大致过程就是这样,如果有遗漏继续补充



单页面改成多页面

改成多页面的话,主要有两个地方需要重新配置

  1. entry入口
    单页面的:
{
	entry: './src/main.js'
}

多页面: 需要把每个文件夹的入口文件都加入,可以写一个方法,获取入口文件夹列表,动态设置

//获取入口文件
function getEntries(){
	const pagesPath = path.resolve('./src/pages')
	var result = fs.readdirSync(path.resolve('./src/pages'))
	var entry = {};
	result.forEach(item => {
		entry[item] = `./src/pages/${item}/main.js`
	})
	return entry // {page1:'./src/pages/.../main.js',page2: './src/pages/.../main.js'}
}

//配置文件里
entry: getEntries()

  1. html-webpack-plugin
//设置HTML模板, 对每个页面添加一个HTML
function htmlPlugins() {
	var arr = []
	Object.keys(baseWebpackConfig['entry']).map(fileName => {
		arr.push(new HtmlWebpackPlugin({
			filename: fileName + '.html', //HTML存放的路径和文件名
			template:  `./src/pages/${fileName}/index.html`, //读取的模板
			chunks: [fileName, 'manifest', 'vendor'], //加载的代码块(只加这些, 不在列表的不加)
			inject: true, //打包文件插入的位置, true,body是在body的最后插入标签,head是在头部
			hash: true, // 为静态资源生成hash值
		}))
	})
	return arr
}

plugins:[...配置的插件].concat(htmlPlugins())

发布了66 篇原创文章 · 获赞 13 · 访问量 6万+

猜你喜欢

转载自blog.csdn.net/haoyanyu_/article/details/97643820