前言:上一篇記錄文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; }) } }}
新聞熱點
疑難解答
圖片精選