作者:花生vs布丁丁7_835 | 来源:互联网 | 2023-07-03 23:37
抽离公共代码 公共代码只需要下载一次就缓存起来了,避免了重复下载。 项目中打包出来的 bundle.js 体积过大,我们可以将一些依赖打包成动态链接库,然后将剩下的第三方依赖拆出来。这样可以有效减小 bundle.js 的体积大小。当然,你还可以继续提取业务代码的公共模块。
module. exports = { optimization: { splitChunks: { cacheGroups: { vendor: { priority: 1 , name: 'vendor' , test: / node_modules / , chunks: 'initial' , minSize: 0 , minChunks: 1 } , common: { chunks: 'initial' , name: 'common' , minSize: 100 , minChunks: 3 } } } } }
exclude/include 通过 exclude、include 配置来确保转译尽可能少的文件。exclude 指定要排除的文件,include 指定要包含的文件。 配置了 include 的比未配置 include 构建更快
const path = require ( 'path' ) ; module. exports = { module: { rules: [ { test: / \.js[x]?$ / , use: [ 'babel-loader' ] , include: [ path. resolve ( __dirname, 'src' ) ] } ] } , }
noParse 如果你使用到了不需要解析的第三方依赖,那么配置 noParse 很显然是一定会起到优化作用的。类似jquery,loash
module. exports = { module: { noParse: / jquery|lodash / } }
IgnorePlugin webpack 的内置插件,作用是忽略第三方包指定目录。
module. exports = { plugins: [ new webpack. IgnorePlugin ( / ^\.\/locale$ / , / moment$ / ) ] }
在使用的时候,如果我们需要指定语言,那么需要我们手动的去引入语言包,例如,引入中文语言包:
import moment from 'moment' ; import 'moment/locale/zh-cn' ;
index.js 中只引入 moment,打包出来的 bundle.js 大小为 263KB,如果配置了 IgnorePlugin,单独引入 moment/locale/zh-cn,构建出来的包大小为 55KB。
externals 我们可以将一些JS文件存储在 CDN 上(减少 Webpack打包出来的 js 体积),在 index.html 中通过
DOCTYPE html > < html lang &#61; " en" > < head> < meta charset &#61; " UTF-8" > < meta name &#61; " viewport" content &#61; " width&#61;device-width, initial-scale&#61;1.0" > < meta http-equiv &#61; " X-UA-Compatible" content &#61; " ie&#61;edge" > < title> Document title> head> < body> < div id &#61; " root" > root div> < script src &#61; " http://libs.baidu.com/jquery/2.0.0/jquery.min.js" > script> body> html>
我们希望在使用时&#xff0c;仍然可以通过 import 的方式去引用(如 import $ from ‘jquery’)&#xff0c;并且希望 webpack 不会对其进行打包&#xff0c;此时就可以配置 externals
//webpack.config.js module.exports &#61; {//...externals: {//jquery通过script引入之后&#xff0c;全局中即有了 jQuery 变量&#39;jquery&#39;: &#39;jQuery&#39;} }
cache-loader 性能开销较大的 loader 之前添加 cache-loader&#xff0c;将结果缓存中磁盘中。默认保存在 node_modueles/.cache/cache-loader 目录下。 babel-loader 配置 cache 的话&#xff0c;也可以不使用 cache-loader&#xff0c;给 babel-loader 增加选项 cacheDirectory
npm install cache- loader - D
DllPlugin DllPlugin 将不会频繁更新的库进行编译&#xff0c;当这些依赖的版本没有变化时&#xff0c;就不需要重新编译。
happypack HappyPack 就能让 Webpack 做到这点&#xff0c;它把任务分解给多个子进程去并发的执行&#xff0c;子进程处理完后再把结果发送给主进程。
npm install happypack - D
HardSourceWebpackPlugin 配置 hard-source-webpack-plugin&#xff0c;首次构建时间没有太大变化&#xff0c;但是第二次开始&#xff0c;构建时间大约可以节约 80%。
npm install hard- source- webpack- plugin - D