前言:上一篇记录文vue-cli 3.0 build包太大导致首屏过长的解决方案中提到了CDN优化,之前是直接在html中手动注入JS,也没有对开发和生产模式进行区分,因为是使用收费的CDN,所以在开发模式会遇到无权使用CDN的问题。要是使用CDN写死在html中,不同环境需要手动的切换CDN,那么早晚有一天会搞乱,下面就说说怎么在vue-cli 3.0 中根据不同环境动态注入CDN。
1. 修改public/index.html
通过htmlwebpackplugin动态注入脚本和样式,index.html如下:
<!DOCTYPE html><html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width,initial-scale=1.0"> <link rel="icon" href="<%= BASE_URL %>favicon.ico" rel="external nofollow" > <title>杭州纳舍科技</title> <!-- 使用CDN的CSS文件 --> <% for (var i in htmlWebpackPlugin.options.cdn && htmlWebpackPlugin.options.cdn.css) { %> <link href="<%= htmlWebpackPlugin.options.cdn.css[i] %>" rel="external nofollow" rel="external nofollow" rel="preload" as="style"> <link href="<%= htmlWebpackPlugin.options.cdn.css[i] %>" rel="external nofollow" rel="external nofollow" rel="stylesheet"> <% } %> <!-- 使用CDN的JS文件 --> <% for (var i in htmlWebpackPlugin.options.cdn && htmlWebpackPlugin.options.cdn.js) { %> <link href="<%= htmlWebpackPlugin.options.cdn.js[i] %>" rel="external nofollow" rel="preload" as="script"> <% } %> </head> <body> <noscript> <strong>We're sorry but ui doesn't work properly without JavaScript enabled. Please enable it to continue.</strong> </noscript> <div class="global-loading"> <div class="spinner"></div> </div> <div id="app"></div> <!-- built files will be auto injected --> <% for (var i in htmlWebpackPlugin.options.cdn && htmlWebpackPlugin.options.cdn.js) { %> <script src="<%= htmlWebpackPlugin.options.cdn.js[i] %>"></script> <% } %> </body></html>
2. 修改vue.config.js配置
首先我们会考虑哪些东西要进行CDN优化,例如我们需要把vue、vue-router、moment
在构建的时候排除在外使用CDN加载这三个库,那么需要把添加externals
const isProduction = process.env.NODE_ENV === 'production';module.exports = { configureWebpack: config => { if (isProduction) { config.externals = { 'vue': 'Vue', 'vue-router': 'VueRouter', 'moment': 'moment' } } }}
现在我们运行npm run build 打包出来的文件就没有Vue、VueRouter、moment,现在我们使用html-webpack-plugin插件进行动态注入CDN,在vue-cli 3.0 中我们要这样配置:
const isProduction = process.env.NODE_ENV === 'production';const cdn = { css: ['xxx.css', 'sss.js'], js: ['xxxx.js', 'sss.js']}module.exports = { configureWebpack: config => { if (isProduction) { config.externals = { 'vue': 'Vue', 'vue-router': 'VueRouter', 'moment': 'moment' } } } chainWebpack: config => { if (isProduction) { config.plugin('html') .tap(args => { args[0].cdn = cdn; return args; }) } }}
新闻热点
疑难解答
图片精选