Configure and use resource CDN in the project built by vue-cli to speed up our project

Configure and use resource CDN in the project built by vue-cli to speed up our project

written in front

Due to the performance requirements of the website, sometimes we don't want some relatively large third-party libraries to be directly packaged bundleinto , but choose to ignore them when packaging and directly use CDNthe above resources.

In the production environment, some third-party packages that the project depends on are replaced cdnby external loading instead of packaging vender, which is very meaningful for improving the loading and response speed of the application.

In vue-cli3and later projects, relevant configurations need vue.config.jsto be performed in this file. If you do not have this file, please create a new one ( package.jsonsame level as ).

Goals

Taking the current common front-end projects as examples, it is recommended to cdnreference ; such as: vue, vuex, vue-router, axios,elementUI ...

target process

1. Configure the modules that need to be taken out

Here we first configureWebpackconfigure externalsthe field of and configure the resources that do not need to be packaged accordingly. As follows:

module.exports = {
    
    
  ...
  configureWebpack: {
    
    
    externals: {
    
    
      'vue': 'Vue',
      'element-ui': 'ELEMENT',
      'vue-router': 'VueRouter',
      'vuex': 'Vuex'
    }
  },
  ...
}

Here we exclude vue, element-ui, vue-routerand vuex.

Questions about how to write this configuration:

Take ignoring when packaging element-uias an example , 'element-ui'it refers importto the global object exposed by this library import ElementUI from 'element-ui'in your statement. You can find this object from the source code of the resource or go to the folder to find the file you need to reference. Next, let 's find the source code under the folder , and the exposed global objects. The following are screenshots of each source code:'element-ui''ELEMENT'element-uicdnnode_modulesnode_moduleselement-uivue-routervuex

When you need to exclude other third-party libraries or plug-ins in the future, you can find the exposed global objects by yourself.

2. Configure the cdn link

externalsAfter configuration, we also need to use htmlWebpackPluginthe ability of to allow us to obtain the cdnresource . First, we vue.config.jsdefine an cdnobject that stores resource connections cdn, as follows:

const cdn = {
    
    
  css: ['//unpkg.com/[email protected]/lib/theme-chalk/index.css'],
  js: [
    '//unpkg.com/[email protected]/dist/vue.min.js',
    '//unpkg.com/[email protected]/dist/vue-router.min.js',
    '//unpkg.com/[email protected]/dist/vuex.min.js',
    '//unpkg.com/[email protected]/lib/index.js'
  ]
}

Secondly, we put cdnthis object into pagethe field in our configuration, the complete configuration is as follows:


const cdn = {
    
    
  css: ['//unpkg.com/[email protected]/lib/theme-chalk/index.css'],
  js: [
    '//unpkg.com/[email protected]/dist/vue.min.js',
    '//unpkg.com/[email protected]/dist/vue-router.min.js',
    '//unpkg.com/[email protected]/dist/vuex.min.js',
    '//unpkg.com/[email protected]/lib/index.js'
  ]
}
 
module.exports = {
    
    
  publicPath: '/',
  productionSourceMap: process.env.NODE_ENV !== 'production',
  devServer: {
    
    
    port: 8077
  },
  chainWebpack: config => {
    
    
    config.resolve.symlinks(true)
  },
  configureWebpack: {
    
    
    externals: {
    
    
      'vue': 'Vue',
      'element-ui': 'ELEMENT',
      'vue-router': 'VueRouter',
      'vuex': 'Vuex'
    }
  },
  pages: {
    
    
    index: {
    
    
      entry: 'src/main.ts',
      template: 'public/index.html',
      filename: 'index.html',
      title: 'sass-admin',
      chunks: ['chunk-vendors', 'chunk-common', 'index'],
      cdn: cdn
    }
  }
}

After doing this, we also need htmlto add the code to generate cssand jsscript at the template of the entry file, such as htmlthe template location here 'public/index.html'.

It is relatively simple here to directly release the complete htmltemplate code, as follows:

<!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.0">
    <link rel="icon" href="<%= BASE_URL %>favicon.ico">
    <title><%= htmlWebpackPlugin.options.title %></title>
    <% for (let i in htmlWebpackPlugin.options.cdn.css) { %>
      <link rel="stylesheet" href="<%= htmlWebpackPlugin.options.cdn.css[i] %>" />
    <% } %>
  </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 (let i in htmlWebpackPlugin.options.cdn.js) { %>
      <script
        type="text/javascript"
        src="<%= htmlWebpackPlugin.options.cdn.js[i] %>"
      ></script>
    <% } %>
  </body>
</html>

in:

  • <%= VALUE %>Used for unescaped interpolation
  • <% expression %>used to describe JavaScriptprocess control

These lodash templateuse the grammar, interested friends can learn more about it, and I won’t expand it here.

After all this is done, we use the packaging analysis tool to analyze bundlethe content .

cdnAnalysis diagram before configuration : Analysis diagram after

configuration :cdn

Through comparison, we found that ours chunk-vendorshas lost the third-party resources we configured in the CDN. Another intuitive comparison is chunk-vendorsthe size of the packaged resources, which will not be expanded here. Another important change is that we have added corresponding resource scripts htmlto the , as shown in the figure:

On the one hand, putting resources on the CDN can reduce the bandwidth consumption of your own server (resources are downloaded from other servers, not your own server), on the other hand, the resources on the CDN are generally not easily modified by you, and the browser After the visit, it will be cached, and the user does not need to download the resource again when the user visits again. The subsequent overall visit speed of the website will be faster, and the CDN can also accelerate it.

—————————— [End of text] ——————————

Recommended reading: Huixin.com (software development blog aggregation-an excellent blog article reading platform for programmers)

Front-end learning exchange group, if you want to come in face-to-face, you can join the group: 832485817 , 685486827 ;
Front-end top learning exchange group (1) Front-end top learning exchange group (2)

Written at the end: convention is better than configuration - the principle of simplicity in software development

—————————— 【End】 ——————————

My:
Personal website: https://neveryu.github.io/neveryu/
Github: https://github.com/Neveryu
Sina Weibo: https://weibo.com/Neveryu
WeChat: miracle421354532

For more learning resources, please pay attention to my Sina Weibo... ok

Guess you like

Origin blog.csdn.net/csdn_yudong/article/details/126781602