vue.config.js

// 是否为生产环境
const isProduction = process.env.NODE_ENV !== 'development';

// 本地环境是否需要使用cdn
const devNeedCdn = false
// cdn链接
const cdn = {
	// cdn:模块名称和模块作用域命名(对应window里面挂载的变量名称)
	externals: {
		vue: 'Vue',
		vuex: 'Vuex',
		'vue-router': 'VueRouter',
		'axios': 'axios',
		'ElementUI': 'element-ui',
	},
	// cdn的css链接
	css: [
		'https://unpkg.com/element-ui/lib/theme-chalk/index.css'
	],
	// cdn的js链接
	js: [
		'https://cdn.bootcss.com/vue/2.6.10/vue.min.js',
		'https://cdn.bootcss.com/vuex/3.1.2/vuex.min.js',
		'https://cdn.bootcss.com/vue-router/3.1.3/vue-router.min.js',
		'https://cdn.bootcss.com/axios/0.19.2/axios.min.js',
		'https://unpkg.com/element-ui/lib/index.js'
	]
}

module.exports = {
	devServer: {
		port: 8889,
	},
	lintOnSave: false,
	publicPath: "/",
	chainWebpack: config => {
		// ============注入cdn start============
		config.plugin('html').tap(args => {
			// 生产环境或本地需要cdn时,才注入cdn
			if (isProduction || devNeedCdn) args[0].cdn = cdn
			return args
		})
	
	},
	configureWebpack: config => {
		// 用cdn方式引入,则构建时要忽略相关资源
		if (isProduction || devNeedCdn) config.externals = cdn.externals
	},
}

index.html

<!-- 使用CDN的CSS文件 -->
		<% for (var i in htmlWebpackPlugin.options.cdn &&
		 htmlWebpackPlugin.options.cdn.css) { %>
		<link href="<%= htmlWebpackPlugin.options.cdn.css[i] %>" rel="external nofollow" rel="stylesheet" />
		<% } %>
		<!-- 使用CDN的CSS文件 -->
		<!-- 使用CDN的JS文件 -->
		<% for (var i in htmlWebpackPlugin.options.cdn &&
		 htmlWebpackPlugin.options.cdn.js) { %>
		<script src="<%= htmlWebpackPlugin.options.cdn.js[i] %>"></script>
		<% } %>
		<!-- 使用CDN的JS文件 -->

注意,cdn的引用必须写在上面

Logo

北京人形旗下天工造物具身智能开源社区,聚焦具身天工与慧思开物两大平台

更多推荐