简述vue2使用webpack脚手架升级至webpack4

第一步、输入命令 vue init webpack demo2 (demo2表示项目名称),回车后等待项目完成创建;

第二步、打开package.json,升级以下依赖(建议升级一项依赖后运行一下项目)

  • webpack系列
    webpack 3.6.0 -> 4.46.0
    webpack-cli -> 3.3.12
    webpack-dev-server 2.9.1 -> 3.11.3
    webpack-marge 4.1.0 -> 4.2.2
    

卸载:npm uninstal webpack webpack-cli webpack-dev-server webpack-merge

安装:npm i -D [email protected] [email protected] [email protected] [email protected]

  • babel系列
    使用命令npx babel-upgrade --write 升级(babel7系列)
  • eslint系列
    eslint 4.15.0 -> 7.32.0
    eslint-config-standard 10.2.1 -> 16.0.3
    eslint-friendly-formatter 3.0.0 -> 4.0.1
    eslint-plugin-import 2.7.0 -> 2.26.0
    eslint-plugin-node 5.2.0 -> 11.1.0
    eslint-plugin-promise 3.4.0 -> 5.2.0
    eslint-plugin-standard 3.0.1 -> 删除
    eslint-plugin-vue 4.0.0 -> 9.7.0
    

卸载:npm uninstall eslint eslint-config-standard eslint-friendly-formatter eslint-plugin-import eslint-plugin-node eslint-plugin-promise eslint-plugin-standard eslint-plugin-vue

安装:npm install -D [email protected] [email protected] [email protected] [email protected] [email protected] [email protected] [email protected]

  • webpack插件系列
    clean-webpack-plugin -> 3.0.0
    copy-webpack-plugin 4.0.1 -> 6.4.1
    extract-text-webpack-plugin -> mini-css-extract-plugin 0.11.0
    friendly-errors-webpack-plugin 1.6.1 -> 1.7.0
    html-webpack-plugin 2.30.1 -> 4.5.0
    optimize-css-assets-webpack-plugin 3.2.0 -> 5.0.8
    uglifyjs-webpack-plugin -> terser-webpack-plugin 4.2.3
    webpack-bundle-analyzer 2.9.0 -> 4.5.0
    

卸载:npm uninstall copy-webpack-plugin extract-text-webpack-plugin friendly-errors-webpack-plugin html-webpack-plugin optimize-css-assets-webpack-plugin uglifyjs-webpack-plugin webpack-bundle-analyzer

安装:npm install -D [email protected] [email protected] [email protected] [email protected] [email protected] [email protected] [email protected] [email protected]

  • loader系列
    babel-loader 8.0.0 -> 8.3.0
    css-loader 0.28.0 -> 3.6.0
    eslint-loader -> eslint-webpack-plugin 2.7.0
    file-loader 1.1.4 -> 6.2.0
    postcss-loader 2.0.8 -> 4.3.0
    style-loader -> 2.0.0
    url-loader 0.5.8 -> 4.1.1
    vue-loader 13.3.0 -> 15.7.0
    

卸载:npm uninstall babel-loader css-loader eslint-loader file-loader postcss-loader url-loader vue-loader

安装:npm install -D [email protected] [email protected] [email protected] [email protected] [email protected] [email protected] [email protected] [email protected]

  • vue系列(根据实际需要升级)
    vue 2.5.2 -> 2.7.8
    vue-template-compiler 2.5.2 -> 2.7.8 (注:和vue版本必须一致)
    vue-router 3.0.1 -> 3.5.1
    vuex 3.6.2
    

卸载:npm uninstall vue vue-template-compiler vue-router vuex

安装:

npm install -D vue-template-compiler@2.7.8
npm install vue@2.7.8 vue-router@3.5.1 vuex@3.6.2
  • 其它依赖
    core-js -> 3.26.1
    less -> 4.1.3
    less-loader -> 7.3.0
    sass -> 1.56.1
    sass-loader -> 10.4.1
    node-sass -> 4.14.1
    

安装:npm install -D [email protected] [email protected] [email protected] [email protected] [email protected] [email protected]

第三步、配置webpack

1、修改build/utils.js文件

1.1 删掉ExtractTextPlugin依赖导入
1.2 添加依赖
	const MiniCssExtractPlugin = require('mini-css-extract-plugin')
1.3 将
    return ExtractTextPlugin.extract({
      use: loaders,
      fallback: 'vue-style-loader'
    }) 
  替换成
    return [MiniCssExtractPlugin.loader].concat(loaders)

2、修改build/webpack.base.conf.js文件

2.1 添加依赖
	const VueLoaderPlugin = require('vue-loader/lib/plugin')
	const ESLintPlugin = require('eslint-webpack-plugin')
2.2 添加plugins代码段
	plugins: [
	    new VueLoaderPlugin(),
	    new ESLintPlugin({
	      fix: true, // 启用ESLint自动修复功能
	      extensions: ['js', 'jsx'],
	      context: resolve('src'), // 文件根目录
	      exclude: ['/node_modules/'], // 指定要排除的文件/目录
	      cache: true //缓存
	    }),
	],
2.3 webpack 4需要添加mode属性
	在module.exports中添加 mode: process.env.NODE_ENV,
2.4 删除代码段1
	const createLintingRule = () => ({
	  test: /\.(js|vue)$/,
	  loader: 'eslint-loader',
	  enforce: 'pre',
	  include: [resolve('src'), resolve('test')],
	  options: {
	    formatter: require('eslint-friendly-formatter'),
	    emitWarning: !config.dev.showEslintErrorsInOverlay
	  }
	})
2.5 删除代码段2
    ...(config.dev.useEslint ? [createLintingRule()] : []),

3、修改build/webpack.dev.conf.js文件

3.1 删除代码
	new webpack.NamedModulesPlugin(), // HMR shows correct file names in console on update.
	new webpack.NoEmitOnErrorsPlugin(),
3.2 修改copy-webpack-plugin代码
	new CopyWebpackPlugin({
      patterns: [
        {
          from: path.resolve(__dirname, '../static'),
          to: config.dev.assetsSubDirectory,
        },
        // 多个资源文件夹可以以对象形式添加
        // {
        //   from: path.resolve(__dirname, '../public'),
        //   to: './',
        // }
      ]
    }),

4、修改build/webpack.prod.conf.js文件

4.1 修改全部依赖
	const path = require('path')
	const utils = require('./utils')
	const webpack = require('webpack')
	const config = require('../config')
	const merge = require('webpack-merge')
	const baseWebpackConfig = require('./webpack.base.conf')
	const CopyWebpackPlugin = require('copy-webpack-plugin')
	const HtmlWebpackPlugin = require('html-webpack-plugin')
	const MiniCssExtractPlugin = require('mini-css-extract-plugin')
	const OptimizeCssAssetsPlugin = require('optimize-css-assets-webpack-plugin')
	const TerserPlugin = require('terser-webpack-plugin')
	const { CleanWebpackPlugin } = require('clean-webpack-plugin')
	const BundleAnalyzerPlugin = require("webpack-bundle-analyzer").BundleAnalyzerPlugin;
4.2 修改Plugins代码部分
	删除所有new webpack.optimize.CommonsChunkPlugin部分
	删除new webpack.optimize.ModuleConcatenationPlugin(),
	添加clean-webpack-plugin、mini-css-extract-plugin、bundleAnalyzerPlugin插件
	修改后plugins代码段:
	plugins: [
	    // http://vuejs.github.io/vue-loader/en/workflow/production.html
	    new webpack.DefinePlugin({
	      'process.env': env
	    }),
	    // 打包时首先将dist文件夹内容清空
	    new CleanWebpackPlugin(),
	    // extract css into its own file
	    new MiniCssExtractPlugin({
	      filename: utils.assetsPath('css/[name].[contenthash].css'),
	    }),
	    // generate dist index.html with correct asset hash for caching.
	    // you can customize output by editing /index.html
	    // see https://github.com/ampedandwired/html-webpack-plugin
	    new HtmlWebpackPlugin({
	      filename: process.env.NODE_ENV === 'testing'
	        ? 'index.html'
	        : config.build.index,
	      template: 'index.html',
	      // favicon: path.resolve(__dirname, '../public/favicon.ico'),
	      inject: true,
	      minify: {
	        removeComments: true,
	        collapseWhitespace: true,
	        removeAttributeQuotes: true
	        // more options:
	        // https://github.com/kangax/html-minifier#options-quick-reference
	      },
	      // necessary to consistently work with multiple chunks via CommonsChunkPlugin
	      chunksSortMode: 'none', // 如果使用webpack4将该配置项设置为'none'
	    }),
	    // keep module.id stable when vendor modules does not change
	    new webpack.HashedModuleIdsPlugin(),
	    // enable scope hoisting
	    // new webpack.optimize.ModuleConcatenationPlugin(),
	    // copy custom static assets
	    new CopyWebpackPlugin({
	      patterns: [
	        {
	          from: path.resolve(__dirname, '../static'),
	          to: config.build.assetsSubDirectory,
	        },
	        // 多个资源文件夹可以以对象形式添加
	        // {
	        //   from: path.resolve(__dirname, '../public'),
	        //   to: './',
	        // }
	      ]
	    }),
	    // webpack-bundle-analyzer
	    // 可以是`server`,`static`或`disabled`。
	    // 在`server`模式下,分析器将启动HTTP服务器来显示软件包报告。
	    // 在“静态”模式下,会生成带有报告的单个HTML文件。
	    new BundleAnalyzerPlugin({
	      analyzerMode: "static",
	      analyzerHost: "127.0.0.1",
	      analyzerPort: 8882, //注意是否有端口冲突
	      reportFilename: "report.html",
	      defaultSizes: "parsed",
	      openAnalyzer: true,
	      generateStatsFile: false,
	      statsFilename: "stats.json",
	      statsOptions: null,
	      logLevel: "info",
	    }),
],
4.3 webpack 4 将CommonsChunkPlugin部分内容放到optimization中了
	添加optimization代码段,与plugins同级:
	optimization: {
	    runtimeChunk: {
	      name: 'runtime'
	    },
	    minimizer: [
	      new TerserPlugin({
	        test: /\.js(\?.*)?$/i,
	        exclude: /\.min\.js$/i, // 过滤掉以".min.js"结尾的文件,
	        parallel: true,
	        sourceMap: config.build.productionSourceMap,
	        extractComments: false, // 是否将注释剥离到单独的文件中
	        terserOptions: {
	          compress: {
	            unused: true,
	            drop_debugger: true, // 移除所有debugger
	            drop_console: true, // 移除所有console
	            pure_funcs: [ // 移除指定的指令,如console, alert等
	              'console.log',
	              'console.error',
	              'console.dir',
	            ],
	          },
	          format: {
	            comments: false, // 删除注释
	          },
	        }
	      }),
	      new OptimizeCssAssetsPlugin({
	        cssProcessorOptions: config.build.productionSourceMap
	          ? { safe: true, map: { inline: false } }
	          : { safe: true, }
	      }),
	    ],
	    splitChunks: {
	      chunks: 'async',
	      minSize: 30000,
	      minChunks: 1,
	      maxSize: 0,
	      maxAsyncRequests: 5,
	      maxInitialRequests: 3,
	      automaticNameDelimiter: '~',
	      name: false,
	      cacheGroups: {
	        vendor: {
	          test: /node_modules\/(.*)\.js/,
	          name: 'vendor',
	          chunks: 'initial',
	          priority: -10,
	          reuseExistingChunk: false,
	        },
	        styles: {
	          test: /\.(less|css|s(a)css)$/,
	          name: 'styles',
	          chunks: 'all',
	          minChunks: 1,
	          reuseExistingChunk: true,
	          enforce: true
	        },
	        default: {
	          minChunks: 2,
	          priority: -20,
	          reuseExistingChunk: true
	        }
	      }
	    }

5、修改config/index.js文件

5.1 修改build下的assetsPublicPath
	assetsPublicPath: '/',  ==>  assetsPublicPath: './',

6、修改根目录下的.babelrc文件

6.1 修改corejs版本为3
	"corejs": 2   ==>  "corejs": 3

7、尝试运行项目:npm run start
简述vue2使用webpack脚手架升级至webpack4_第1张图片
8、尝试打包项目:npm run build
简述vue2使用webpack脚手架升级至webpack4_第2张图片

案例地址:https://gitee.com/alertcaikh/vue2-webpack4-demo2

小贴士:工具可以千千万万,但是核心知识点基本不变;学好JS,走遍前端都不怕!

你可能感兴趣的:(Webpack,Vue2,webpack,vue.js,javascript)