解决webpack打包体积过大的问题

项目中引用了vue、vue-router、axios、element-ui、qs等第三方库,导致打包后文件体积过大。

1 通过cdn引入第三方库。

1.1 在/build/webpack.base.conf.js中,配置externals

配置cdn主要利用了externals(外部的)选项,key表示的是包名,即package.json中包的名称,value表示的是包导出的类名。比如说vue包导出的类名是Vue,vue-router导出的类名是VueRouter。类名很重要,不能乱写,不然就会报找不到变量的错。

// externals中的key是后面需要require的名字,value是第三方库暴露出来的方法名
module.exports = {
  //...
  externals: {
    'vue': 'Vue',
    'vue-router': 'VueRouter',
    'axios': 'axios',
    'element-ui': 'Element',
    'qs': 'Qs'
  }
}


1.2 在/src/main.js和/src/router/index.js中,移除上面与之相关的import引入,改为require方式引入

// /src/main.js
// 移除
import Vue from 'vue'
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
import axios from 'axios'
import Qs from 'qs'
Vue.use(ElementUI)

// 添加
const Vue = require('vue')
const ElementUI = require('element-ui')
const axios = require('axios')
const Qs = require('qs')

 

// /src/router/index.js
// 移除
import Router from 'vue-router'
Vue.use(Router)
// 添加
const Router = require('vue-router')


1.3 在/index.html中,通过CDN引入相应的js文件和css文件(CDN地址:https://www.bootcdn.cn)

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width,initial-scale=1.0">
    <title>配置webpack中externals来减少打包后vendor.js的体积</title>
    <!-- 引入样式 -->
    <link href="https://cdn.bootcss.com/element-ui/2.12.0/theme-chalk/index.css" rel="stylesheet">
  </head>
  <body style="margin: 2px">
    <div id="app">
    </div>
    <script src="https://cdn.bootcss.com/vue/2.6.10/vue.min.js"></script>
    <script src="https://cdn.bootcss.com/vue-router/3.1.3/vue-router.min.js"></script>
    <script src="https://cdn.bootcss.com/axios/0.19.0/axios.min.js"></script>
    <script src="https://cdn.bootcss.com/element-ui/2.12.0/index.js"></script>
    <script src="https://cdn.bootcss.com/qs/6.8.0/qs.min.js"></script>
  </body>
</html>

2 使用路由懒加载

像vue这种单页面应用,如果没有懒加载,运用webpack打包后的文件将会异常的大, 造成进入首页时,需要加载的内容过多,时间过长,会出现长时间的白屏。 而运用懒加载则可以将页面进行划分,需要的时候加载页面,可以有效的分担首页所承担的加载压力,减少首页加载用时。

简单的说就是:进入首页不用一次加载过多资源造成用时过长

将/router/index.js下的路由配置改为如下

const router = new Router({
    routes: [
         {
               path: '/',
               name: 'HelloWorld',
               component: (resolve) => {
                   require(['../components/HelloWorld'], resolve) // 这里是你的模块 不用import去引入了
               }
           }
    ]
})

const HelloWorld = () => import("@/components/HelloWorld");
export default new Router({
  routes: [{
    path: '/',
    name: 'HelloWorld',
    component: HelloWorld
  }]
})

 

3 开启gzip压缩

3.1 打开config / index.js 文件

把productionGzip设置为true,

productionGzip: true

3.2 输入命令对插件进行安装

npm install --save-dev compression-webpack-plugin@1.1.12

 

 

最后 run build吧

<think>好的,我需要帮助用户寻找优化Webpack打包体积的方法。根据用户提供的引用资料,我需要整合这些信息并给出具体的步骤和最佳实践。首先,用户提到了使用webpack-bundle-analyzer来分析打包文件,这应该是第一步。接着,引用[2]和[3]提到了配置Webpack的插件,比如WebpackBundleSizeAnalyzerPlugin。引用[4]提到了image-webpack-loader来压缩图片。此外,可能还有其他方法,比如代码分割、Tree Shaking、压缩代码等。需要确保所有建议都符合用户提供的引用内容,并且步骤清晰。还需要注意用户提到的LaTeX格式要求,但这里可能不太需要数学公式,除非涉及性能指标。最后要生成相关问题,确保问题与优化Webpack打包相关。现在整理步骤,确保每个步骤都有对应的引用支持,并按照用户的要求结构回答。</think>### 优化Webpack打包体积的方法及最佳实践 #### 1. **使用分析工具定位体积问题** - **安装webpack-bundle-analyzer** 通过可视化工具分析打包文件的组成,定位体积较的模块。安装命令如下: ```bash npm install --save-dev webpack-bundle-analyzer ``` 在`webpack.config.js`中配置插件[^1][^3]: ```javascript const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin; module.exports = { plugins: [new BundleAnalyzerPlugin()] }; ``` - **使用WebpackBundleSizeAnalyzerPlugin** 进一步分析各依赖项的体积占比[^3]: ```javascript const WebpackBundleSizeAnalyzerPlugin = require('webpack-bundle-size-analyzer').WebpackBundleSizeAnalyzerPlugin; module.exports = { plugins: [new WebpackBundleSizeAnalyzerPlugin('./report.txt')] }; ``` #### 2. **压缩图片资源** - **配置image-webpack-loader** 使用`image-webpack-loader`自动压缩图片体积,降低资源占用[^4]: ```javascript module.exports = { module: { rules: [ { test: /\.(png|jpe?g|gif|svg)$/, use: [ { loader: 'image-webpack-loader', options: { bypassOnDebug: true } } ] } ] } }; ``` #### 3. **代码分割与Tree Shaking** - **代码分割(Code Splitting)** 将代码按路由或功能拆分为多个块,实现按需加载。例如,使用Webpack的`SplitChunksPlugin`: ```javascript module.exports = { optimization: { splitChunks: { chunks: 'all' } } }; ``` - **Tree Shaking** 通过ES6模块化语法(`import/export`)删除未使用的代码。确保`webpack.config.js`中`mode`设为`production`以自动启用[^2]。 #### 4. **压缩代码与提取公共依赖** - **使用TerserPlugin压缩JS** 生产模式下Webpack默认启用代码压缩,也可手动配置: ```javascript const TerserPlugin = require('terser-webpack-plugin'); module.exports = { optimization: { minimize: true, minimizer: [new TerserPlugin()] } }; ``` - **提取CSS为单独文件** 使用`mini-css-extract-plugin`将CSS从JS中分离,避免重复打包: ```javascript const MiniCssExtractPlugin = require('mini-css-extract-plugin'); module.exports = { plugins: [new MiniCssExtractPlugin()], module: { rules: [ { test: /\.css$/, use: [MiniCssExtractPlugin.loader, 'css-loader'] } ] } }; ``` #### 5. **优化第三方库体积** - **按需引入(如Lodash)** 使用`babel-plugin-lodash`仅引入需要的函数: ```javascript // .babelrc { "plugins": ["lodash"] } ``` - **使用CDN加载型库(如Vue、React)** 通过`externals`配置排除已通过CDN引入的库: ```javascript module.exports = { externals: { 'vue': 'Vue', 'react': 'React' } }; ``` --- ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值