vue打包cdn优化
这里的例子是对vue,vue-router,element-ui的cdn引入
-
安装webpack-bundle-analyzer,参考地址:https://github.com/webpack-contrib/webpack-bundle-analyzer
-
设置vue.config.js,参考地址:https://cli.vuejs.org/zh/config/#configurewebpack
main.js
import Vue from "vue"; import App from "./App.vue"; import router from "./router"; import { store } from "./store/index"; import ElementUI from "element-ui"; import Vuex from "vuex"; Vue.use(ElementUI); Vue.use(Vuex); Vue.config.productionTip = false; new Vue({ store, router, render: (h) => h(App), }).$mount("#app");
vue.config.js
const BundleAnalyzerPlugin = require("webpack-bundle-analyzer").BundleAnalyzerPlugin; module.exports = { //运行打包后的html必须要写 //参考网址:https://cli.vuejs.org/zh/config/#publicpath publicPath: "./", configureWebpack: { externals: { //左边是import右边的值,右边是你定义的全局变量 "vue": "Vue", //element-ui比较特殊,右边固定ELEMENT,与你定义的全局变量无关 "element-ui": "ELEMENT", "vue-router": "VueRouter", }, plugins: [new BundleAnalyzerPlugin()], }, };
-
在public/index.html 注入cdn
<!DOCTYPE html> <html lang=""> <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" /> <title><%= htmlWebpackPlugin.options.title %></title> </head> <body> <noscript> <strong >We're sorry but <%= htmlWebpackPlugin.options.title %> doesn't work properly without JavaScript enabled. Please enable it to continue.</strong > </noscript> <div id="app"></div> <!-- built files will be auto injected --> <script src="https://cdn.jsdelivr.net/npm/vue@2"></script> <!-- 引入样式 --> <link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css" /> <!-- 引入组件库 --> <script src="https://unpkg.com/element-ui/lib/index.js"></script> <script src="https://unpkg.com/vue-router@3.2.0/dist/vue-router.js"></script> </body> </html>
注意
- 使用cdn时,要注意cdn引入的版本和你npm i 的版本是否一致
- cdn的资源可以参考bootCDN 地址:https://www.bootcdn.cn/