vue-cli3打包项目使用CDN的方式引入框架文件

1.在vue.config.js中使用chainWebpack添加externals配置

module.exports = {
    chainWebpack: config => {
        if (process.env.NODE_ENV === 'production') {
            // #region 忽略生成环境打包的文件
            var externals = {
                'vue': 'Vue',
                'axios': 'axios',
                'element-ui': 'ELEMENT',
                'vue-router': 'VueRouter',
                'vuex': 'Vuex',
                'echarts': 'echarts'
            }
            config.externals(externals)

            // 在html文件中引入相关CDN
            const cdn = {
                css: [
                    // element-ui css
                    'https://cdn.bootcss.com/element-ui/2.13.0/theme-chalk/index.css'
                ],
                js: [
                    // vue
                    'https://cdn.staticfile.org/vue/2.5.22/vue.min.js',
                    // vue-router
                    'https://cdn.staticfile.org/vue-router/3.0.2/vue-router.min.js',
                    // vuex
                    'https://cdn.staticfile.org/vuex/3.1.0/vuex.min.js',
                    // axios
                    'https://cdn.staticfile.org/axios/0.19.0-beta.1/axios.min.js',
                    // element-ui js
                    'https://cdn.bootcss.com/element-ui/2.13.0/index.js',
                    //echarts
                    'https://cdn.bootcss.com/echarts/4.6.0/echarts-en.common.js'
                ]
            }
            config.plugin('html')
                .tap(args => {
                    args[0].cdn = cdn
                    return args
                })
        }
    },

    //...省略的其它代码

}

2.在项目index.html主页中引入CDN资源


<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">
    <% if (process.env.NODE_ENV === 'production') { %>

      <% for(var css of htmlWebpackPlugin.options.cdn.css) { %>
        <link href="<%=css%>" rel="preload" as="style">
        <link rel="stylesheet" href="<%=css%>" as="style">
      <% } %>
      <% for(var js of htmlWebpackPlugin.options.cdn.js) { %>
        <link href="<%=js%>" rel="preload" as="script">
        <script src="<%=js%>">script>
      <% } %>

    <% } %>
    <title>bxxttitle>
  head>
  <body>
    <noscript>
      <strong>We're sorry but bxxt doesn't work properly without JavaScript enabled. Please enable it to continue.strong>
    noscript>
    <div id="app">div>
    
  body>
html>

3.将先前引入的框架文件代码注释掉再进行打包

// elemntui组件库,打包部署采用cdn需注释掉
// import ElementUI from 'element-ui';
// import 'element-ui/lib/theme-chalk/index.css';
// import 'element-ui/lib/theme-chalk/display.css';
// Vue.use(ElementUI);

4.打包

$ npm run build

你可能感兴趣的:(性能优化,vue-cli)