const isProd = process.env.NODE_ENV === 'production'
//样式和JavaScript脚本的第三方cdn连接
const cdn = {
css: ['https://cdn.jsdelivr.net/npm/element-ui@2.15.0/lib/theme-chalk/index.css'],
js: [
'https://cdn.jsdelivr.net/npm/vue@2.6.12/dist/vue.min.js',
'https://cdn.jsdelivr.net/npm/vue-router@3.5.1/dist/vue-router.min.js',
'https://cdn.jsdelivr.net/npm/vuex@3.6.2/dist/vuex.min.js',
'https://cdn.jsdelivr.net/npm/axios@0.21.1/dist/axios.min.js',
'https://cdn.jsdelivr.net/npm/element-ui@2.15.0/lib/index.js'
]
}
//外部引入的对象与内部引用时的对象配置
//例如:{vue: 'Vue'},vue为内部import 'vue'的vue对象,Vue为外部引入后的对应的全局变量。
const externals = {
vue: 'Vue',
'vue-router': 'VueRouter',
vuex: 'Vuex',
axios: 'axios',
'element-ui': 'ELEMENT'
}
module.exports = {
configureWebpack: {
//外部扩展的配置,告诉webpack,在production模式下,才引入外部的cdn资源,并且不要把对应的模块打包到vender的公共包里面
externals: isProd ? externals : {}
},
chainWebpack: webpackConfig => {
if (isProd) {
webpackConfig.plugin('html').tap(args => {
args[0].cdn = cdn
return args
})
}
},
devServer: {
open: true,
host: '0.0.0.0',
port: 8081
}
}
2 index.html文件的相应配置
<!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>
<% for(var i in htmlWebpackPlugin.options.cdn && htmlWebpackPlugin.options.cdn.css){ %>
<link rel="stylesheet" href="<%= htmlWebpackPlugin.options.cdn.css[i] %>" ref="preload"/>
<% } %>
</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 -->
<% for(var i in htmlWebpackPlugin.options.cdn && htmlWebpackPlugin.options.cdn.js){ %>
<script type="text/javascript" src="<%= htmlWebpackPlugin.options.cdn.js[i] %>" ref="preload"></script>
<% } %>
</body>
</html>
2.1引入cdn的css
<% for(var i in htmlWebpackPlugin.options.cdn && htmlWebpackPlugin.options.cdn.css){ %>
<link rel="stylesheet" href="<%= htmlWebpackPlugin.options.cdn.css[i] %>" ref="preload"/>
<% } %>
2.2 引入cdn的js
<% for(var i in htmlWebpackPlugin.options.cdn && htmlWebpackPlugin.options.cdn.js){ %>
<script type="text/javascript" src="<%= htmlWebpackPlugin.options.cdn.js[i] %>" ref="preload"></script>
<% } %>
如果对您有帮助,请点个赞,谢谢。