1、package.json的文件:
{
"name": "cdn-test",
"version": "0.1.0",
"private": true,
"scripts": {
"serve": "vue-cli-service serve",
"build": "vue-cli-service build --report"
},
"dependencies": {
"axios": "^0.27.2",
"core-js": "^3.6.5",
"element-plus": "^2.2.2",
"vue": "^3.0.0",
"vue-router": "^4.0.0-0",
"vuex": "^4.0.0-0"
},
"devDependencies": {
"@vue/cli-plugin-babel": "~4.5.15",
"@vue/cli-plugin-router": "~4.5.15",
"@vue/cli-plugin-vuex": "~4.5.15",
"@vue/cli-service": "~4.5.15",
"@vue/compiler-sfc": "^3.0.0",
"sass": "^1.26.5",
"sass-loader": "^8.0.2"
}
}
<%= htmlWebpackPlugin.options.title %>
提供加载外部js全部挂载到window对象上,externals对象里面的属性的值对应着window对象上的属性如下:
externals:{
"vue":"Vue",
"axios":"axios",
"vuex":"Vuex",
"vue-router":"VueRouter",
"element-plus": "ElementPlus"
}
不需要通过配置externals:使用第三方包的方式,比如访问vue:
const {ref, reactive, watch, computed, onMounted}=window.Vue;
传入打包参数“report” 如:vue-cli-service build --report,就会生成一个l分析报告文件report.htm
在浏览器打开分析报告如下图:
通过cdn的方式引入第三方插件(包)报告如下:
引入步骤:
1、public/index.html文件:
<%= htmlWebpackPlugin.options.title %>
2、vue.config.js
const Timestamp = new Date().getTime();
module.exports={
publicPath:'./',
configureWebpack:{
externals:{
"vue":"Vue",
"axios":"axios",
"vuex":"Vuex",
"vue-router":"VueRouter",
"element-plus": "ElementPlus"
},
output: { // 输出重构 打包编译后的 文件名称 【模块名称.时间戳】
filename: `[name].${Timestamp}.js`,
chunkFilename: `[name].${Timestamp}.js`
}
}
}
运行效果:
以上2步就可以让打包文件体积变小。
至于webpack-bundle-analyzer插件只是帮我们自动打开report.html,对以上的目的没有任何作用,不需要配置运行参数--report。只要npm run xx 都会打开分析报告
webpack-bundle-analyzer的安装:
npm install --save-dev webpack-bundle-analyzer
webpack-bundle-analyzer插件的配置:
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
plugins:[
new BundleAnalyzerPlugin();
]
BootCDN - Bootstrap 中文网开源项目免费 CDN 加速服务