webpack性能优化之CDN

153 阅读1分钟

介绍

CDN称之为内容分发网络(Content Delivery Network或Content Distribution Network,缩写:CDN)

主要利用最靠近每个用户的服务器,更快、更可靠地将音乐、图片、视频、应用程序及其他文件发送给用户,来提供高性能、可扩展性及低成本的网络内容传递给用户。

1.如果想要将打包后的静态资源放置CDN服务器,如何进行配置?

这里就需要用到publicPath。

module.exports={
	entry:'xxx',
	output:{
		path:path.resovle(__dirname,'./build')
		filename:'[id]_bundle.js'
		publicPath:"http://cdnAddress.com/"
	}
}

publicPath 用于指定在访问输出文件时的公共路径(URL 前缀)

打包后,index.html中的引入js文件会是如下

<script src="http://cdnAddress.com/index_bundle.js"></script>

如果原本没写publicPath,打包后就是如下,所以publicPath就是给路径加上一个公共前缀(所有的资源都会)

<script src="/index_bundle.js"></script>

2.不打包第三方库,直接使用cdn引入

对于一些第三方的库,我们也不需要打包,直接用cdn引入,所以需要在webpack中配置排除打包这些第三方库

module.exports={
	entry:...,
        output:...
	
	externals:{
		lodash:'_',
		dayjs:'dayjs',
		axios:'axios',
	}
}

externals里面配置的键值对需要有严格规定,例如lodash:'__',。这个lodash是导入的第三方库的名字,”_“是里面的某个变量,一般的导入方式如下

import _ from 'lodash'

image.png

最后只需要将这些包通过cdn在index.html中引入即可