❤vue2项目webpack打包的优化策略

❤ vue2项目webpack打包的优化策略

(优化前)

现在我们的打包时间为:
在这里插入图片描述>打包体积大小为:
在这里插入图片描述

1、去除开发环境和生产环境提示以及日志

开发环境和生产环境的打印处理

生产环境去除console.log打印的两种方式

通过环境变量控制console.log的打印,具体操作如下:

第一种

1、根目录 .env.xxx文件中写入NODE_ENV参数
在这里插入图片描述

2、在main.js里面加上下列语句:

if (process.env.NODE_ENV === 'production') {
  console.log = () => {}
  console.warn = () => {}
}

以上完成了配置

第二种

在babel.config.js 文件中进行修改

1、需下载这个包transform-remove-console
```js
npm install babel-plugin-transform-remove-console --save-dev

2、在babel.config.js可如下写


// babel.config.js
// 生产环境移除console
const remPlugins = []
if (process.env.NODE_ENV === 'production') {
    remPlugins.push('transform-remove-console')
}
 
module.exports = {
  "plugins":[
  ...remPlugins 
  ]
};

根据当前的开发模式或打包模式来使用不同的入口文件

module.exports = {
  chainWebpack: config => {
    // 打包模式
    config.when(process.env.NODE_ENV === 'production', config => {
      config
        .entry('app')
        .clear()
        .add('./src/main-prod.js')
    })
    // 开发模式
    config.when(process.env.NODE_ENV === 'development', config => {
      config
        .entry('app')
        .clear()
        .add('./src/main-dev.js')
    })
  }
}

2、 build后不可查看源码

不设置的情况下,打包上线,可在 f12 -> sources -> webpack:// 下查看到项目源码

在这里插入图片描述
在vue.config.js中配置

const isProduction = process.env.NODE_ENV === 'production'
module.exports = {
	productionSourceMap: false,
	configureWebpack: {
		devtool: isProduction ? false : "source-map",
	}
}

3、解决每次发版都要强刷清除浏览器缓存

原理
将打包后的js和css文件,加上打包时的时间戳

1 index.html
在 public 目录下的index.html文件里添加如下代码

<meta http-equiv="pragram" content="no-cache">
<meta http-equiv="cache-control" content="no-cache, no-store, must-revalidate">
<meta http-equiv="expires" content="0">

vue.config.js

let timeStamp = new Date().getTime();
module.exports = {
    publicPath: "./",
    filenameHashing: false,
    // 打包配置
    configureWebpack: {
        output: { // 输出重构 打包编译后的js文件名称,添加时间戳.
            filename: `js/js[name].${timeStamp}.js`,
            chunkFilename: `js/chunk.[id].${timeStamp}.js`,
        }
    },
    css: {
        extract: { // 打包后css文件名称添加时间戳
            filename: `css/[name].${timeStamp}.css`,
            chunkFilename: `css/chunk.[id].${timeStamp}.css`,
        }
    }
};

4、配置Vue2项目打包优化命令行(Tree-shaking)

Tree-shaking 是一种通过静态分析代码来检测未使用部分的技术

(1)添加–report命令:“build”: “vue-cli-service build --report”,打包后 dist 目录会生成 report.html 文件,用来分析各文件的大小
在这里插入图片描述

打开以后如图所示
在这里插入图片描述

5、配置V2打包优化对比工具webpack-bundle-analyzer ((Tree-shaking))

webpack有一种可视化的打包分析工具:webpack-bundle-analyzer ,在vue.config.js中引入,代码如下:npm run build的时候会出现打包分析图

npm install webpack-bundle-analyzer -D
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;

module.exports = {
configureWebpack: {
        plugins: [
            new BundleAnalyzerPlugin()
        ]
    }        
}

6、externals 提取公共依赖包

在我打包之前项目体积如图
在这里插入图片描述
vue.config.js 中配置

configureWebpack: {
    name: name,
    resolve: {
      alias: {
        '@': resolve('src')
      }
    },
    externals: {
      vue: 'Vue',
      'vue-router': 'VueRouter',
      axios: 'axios',
      echarts: 'echarts'
    },
    // 打包插件
    // plugins: [newBundleAnalyzerPlugin],
  },

在 index.html 中使用 CDN 引入依赖


vue
<script type="text/javascript" src="https://lib.baomitu.com/vue/2.6.10/vue.min.js"></script>

vue-router
 <script type="text/javascript" src="https://lib.baomitu.com/vue-router/3.0.2/vue-router.min.js"></script>

axios   
 <script type="text/javascript" src="https://lib.baomitu.com/axios/0.18.1/axios.min.js"></script>

echarts
<script type="text/javascript" src="https://lib.baomitu.com/echarts/4.7.0/echarts.min.js"></script>

配置后如图
在这里插入图片描述

7、babel-plugin-component(未使用)

通过该插件,最终只引入指定组件和样式,来实现减少组件库体积大小

// 安装
npm install babel-plugin-component -D

babel.config.js中引入

plugins: [
    'component',
    {
      'libraryName': 'element-ui',
      'styleLibraryName': 'theme-chalk',
    }
  ],

8、使用 moment-locales-webpack-plugin插件,剔除掉无用的语言包

安装
npm install moment-locales-webpack-plugin -D

vue.config.js 中引入

constMomentLocalesPlugin = require( 'moment-locales-webpack-plugin');
module.exports = {
configureWebpack: {
	plugins: [
	newMomentLocalesPlugin({ localesToKeep: [ 'zh-cn']})
	]
}
}

9、HappyPack 多线程打包(提升打包速度)

由于运行在 Node.js 之上的 webpack 是单线程模型的,我们需要 webpack 能同一时间处理多个任务,发挥多核 CPU 电脑的威力

HappyPack就能实现多线程打包,它把任务分解给多个子进程去并发的执行,子进程处理完后再把结果发送给主进程,来提升打包速度

vue2

安装
npm install happypack -D

//vue.config.js中进行配置

//顶部引入
const HappyPack = require('happypack');
const happyThreadPool = HappyPack.ThreadPool({ size: os.cpus().length });
const os = require('os');

chainWebpack(config){
		config.plugin('happypack')
			.use(HappyPack)
			.tap(options=>{
				options[0]={
					id:'babel',
					loaders:['babel-loader?cacheDirectory=true'],
					threadPool: happyThreadPool
				}
				return options
			})
		const hRule = config.module.rule('js')
		hRule.test(/\.js$/)
			.include.add(resolve('src'))
			.end()
		hRule.uses.clear()
		hRule.use('happypack/loader?id=babel')
			.loader('happypack/loader?id=babel')
			.end()
}
安装
npm install happypack -D

vue.config.js 中引入

constHappyPack = require( 'happypack');
constos = require( 'os');
consthappyThreadPool = HappyPack.ThreadPool({ size: os.cpus.length });

10、Gzip压缩

安装
npm install compression-webpack-plugin -D

vue.config.js 中引入

// 引入
const CompressionPlugin = require( 'compression-webpack-plugin');
 

//使用
  configureWebpack: { 
    // 打包插件
    plugins:[
      new CompressionPlugin({
      test: /\.(js|css)(\?.*)?$/i, //需要压缩的文件正则
      threshold: 1024, //文件大小大于这个值时启用压缩
      deleteOriginalAssets: false//压缩后保留原文件
      })
    ],
}
  • 16
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
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` 来打包我们的项目了。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

林太白

感谢打赏,你拥有了我VIP权限

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

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

打赏作者

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

抵扣说明:

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

余额充值