简述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 webpack@4.30.0 webpack-cli@3.3.12 webpack-dev-server@3.11.3 webpack-merge@4.2.2

  • 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 eslint@7.32.0 eslint-config-standard@16.0.3 eslint-friendly-formatter@4.0.1 eslint-plugin-import@2.26.0 eslint-plugin-node@11.1.0 eslint-plugin-promise@5.2.0 eslint-plugin-vue@9.7.0

  • 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 clean-webpack-plugin@3.0.0 copy-webpack-plugin@5.1.2 mini-css-extract-plugin@0.11.0 friendly-errors-webpack-plugin@1.7.0 html-webpack-plugin@4.5.0 optimize-css-assets-webpack-plugin@5.0.8 terser-webpack-plugin@4.2.3 webpack-bundle-analyzer@4.5.0

  • 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 babel-loader@8.3.0 css-loader@3.6.0 eslint-webpack-plugin@2.7.0 file-loader@6.2.0 postcss-loader@4.3.0 style-loader@2.0.0 url-loader@4.1.1 vue-loader@15.7.0

  • 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 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

第三步、配置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
成功运行
8、尝试打包项目:npm run build
成功打包

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

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

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
Vue2 项目可以使用 webpack 来进行打包。下面是一个基本的 Vue2 + webpack 的项目结构: ``` - src - assets - images - styles - components - router - store - views - App.vue - main.js - index.html - package.json - webpack.config.js ``` 其中: - `src` 目录是我们源代码的目录,包含了所有 Vue2 组件、路由、状态管理、样式等文件; - `index.html` 是我们的 HTML 页面; - `package.json` 是我们的项目配置文件,包含了我们的依赖和启动命令; - `webpack.config.js` 是我们的 webpack 配置文件,包含了我们的入口、输出、loader、插件等配置。 下面是一个简单的 webpack 配置文件示例: ```javascript const path = require('path'); const HtmlWebpackPlugin = require('html-webpack-plugin'); module.exports = { entry: './src/main.js', output: { path: path.resolve(__dirname, 'dist'), filename: 'bundle.js', }, module: { rules: [ { test: /\.vue$/, loader: 'vue-loader', }, { test: /\.js$/, loader: 'babel-loader', exclude: /node_modules/, }, { test: /\.(png|jpe?g|gif)$/i, loader: 'file-loader', options: { name: '[name].[ext]', outputPath: 'images', }, }, { test: /\.css$/, use: ['style-loader', 'css-loader'], }, ], }, plugins: [ new HtmlWebpackPlugin({ template: 'index.html', }), ], devServer: { contentBase: path.join(__dirname, 'dist'), compress: true, port: 9000, }, }; ``` 在 `package.json` 中,我们可以定义一些启动命令,比如: ```json { "scripts": { "dev": "webpack-dev-server --mode development", "build": "webpack --mode production" } } ``` 这样,我们就可以使用 `npm run dev` 来启动开发服务器,以及使用 `npm run build` 来打包我们的项目了。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Alert.GoSt

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值