vue-cli使用cdn优化

tech2023-11-27  41

首先创建vue.config.js

在vue.config.js中配置

先把你要加载的cdn链接写好

// vue.config.js const cdn = { css: [ "//cdn.jsdelivr.net/npm/vant@2.8.6/lib/index.css", "//unpkg.com/nprogress@0.2.0/nprogress.css" ], js: [ "//unpkg.com/vue@2.6.11/dist/vue.min.js", "//unpkg.com/vue-router@3.2.0/dist/vue-router.min.js", "//unpkg.com/vuex@3.4.0/dist/vuex.min.js", "//cdn.jsdelivr.net/npm/vant@2.8.6/lib/vant.min.js", "//unpkg.com/axios/dist/axios.min.js", "//api.map.baidu.com/api?v=2.0&ak=X03y57Hm1659cLPAZF5FHZWAkRYltwA7&s=1", "//unpkg.com/nprogress@0.2.0/nprogress.js" ] }

注:cdn的版本号要和package.json中的依赖包版本一致,不然会出现一些奇怪的问题

在configureWebpack中配置externals,把你不想打包的模块配置进去

// vue.config.js module.exports = { publicPath: "./", // 项目部署的基础路径 outputDir: "dist", lintOnSave: false, productionSourceMap: process.env.NODE_ENV !== 'production', devServer: { port: 1122, // 端口号 https: false, // https:{type:Boolean} open: true, //配置自动启动浏览器 hot:true, }, configureWebpack:{ externals: { "BMap": "BMap", vue: "Vue", "vant": "vant", "vue-router": "VueRouter", vuex: "Vuex", axios: "axios", nprogress:"nprogress" } }, pages: { index: { cdn: cdn } } };

然后在项目的index.html引入各个cdn链接

<!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, maximum-scale=1, minimum-scale=1, user-scalable=no"> <link rel="icon" href="<%= BASE_URL %>favicon.ico"> <% for (let i in htmlWebpackPlugin.options.cdn.css) { %> <link rel="stylesheet" href="<%= htmlWebpackPlugin.options.cdn.css[i] %>" /> <% } %> <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" class="hs"></div> <% for (let i in htmlWebpackPlugin.options.cdn.js) { %> <script type="text/javascript" src="<%= htmlWebpackPlugin.options.cdn.js[i] %>" ></script> <% } %> </body> </html>

现在基本就已经配置好了,

项目里可不用import Vue from 'vue’之类的引用了,因为已经使用cdn了,可以直接使用你cdn引用的那些模块,比如在main.js中直接打印Vue,也可以打印出来

最新回复(0)