Vue Packaging Optimization - CDN Acceleration

Reason for optimization

The packaged data is as follows before CDN acceleration is not used. It can be seen that the dependencies of element-ui, vue, vuex, and vue-router are all entered into chunk-vendors.js, resulting in a large volume. If there are more dependencies, are they bigger? , and will also affect the loading speed of the first screen of a single-page application, so one of the packaging optimization methods is used here to separate dependencies.

insert image description here

View dependency version

First of all, dependencies need to be used in the project. In my project here, I plan to separate the dependencies of element-ui, vue, vuex, and vue-router, and record the dependency version for later use.

dependent name Dependency version
vue 2.6.11
vue-router 3.2.0
vuex 3.4.0
element-ui 2.15.9

insert image description here

View dependency references

These dependencies can be seen referenced in main.js.
Some configurations of the development environment and the production environment in the project are different, so the screenshot here is convenient for later understanding.

insert image description here

Configure development and production environments

Above we have seen how to reference dependencies in main.js, now we need to make some changes in main.js to main-dev.js as our development environment, and then create a new file called main in the same directory -prod.js is our production environment. In actual development, the configuration of the development environment (main-dev.js) and production environment (main-prod.js) is different.

Development environment entry - main-dev.js

insert image description here

// 这是给ElementUI组件库组件设置默认参数
Vue.use(ElementUI, {
    
     size: 'small', zIndex: 3000 });

Production environment entry - main-prod.js

insert image description here

// 这是给ElementUI组件库组件设置默认参数(cdn加速和生产环境配置有区别)
Vue.prototype.$ELEMENT = {
    
    
  size: 'small',
  zIndex: 3000
};

Configure the development environment entry and production environment entry

What you need to pay attention to here is the configuration entry, because the default entry file has only one main.js but you changed it to main-dev.js and added a main-prod.js, then you will definitely report an error when you run the project or package the project , because it can’t find main.js, so here you need to specify the production environment and development environment entry through the vue.config.js file.

view.config.js

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

module.exports = {
    
    
    publicPath: './', // 不加这个可能会导致静态资源找不到的情况。
    chainWebpack: config => {
    
    
        config.when(isProduction, config => {
    
    
        	// 如果是生产环境,那么将main-prod.js作为入口文件(我这里是ts和js一样)。
            config.entry('app').clear().add('./src/main-prod.ts');
        });
        config.when(!isProduction, config => {
    
    
        	// 如果是不是生产环境,那么将main-dev.js作为入口文件(我这里是ts和js一样).
            config.entry('app').clear().add('./src/main-dev.ts');
        });
    }
};

insert image description here

Configure CDN acceleration

The completion of the above environment configuration is half successful, and the next step is to configure the cdn acceleration related.

view.config.js

I need to explain here. Is the dependent version in the cdn acceleration link below the same as the dependent version table displayed above? It must be the same, otherwise what should I do if there is a conflict of dependency versions.
The externals attribute tells webpack the dependency names that need to be excluded and the object attribute names mounted on the window. Here is a simple list of commonly used tables. If you need other object names that can be exported to the window by plug-in dependencies, you can also search for the corresponding ones on Baidu. Object property name.

dependent name The property name of the object mounted on the window
vue Vue
vue-router VueRouter
vuex Vuex
Lodash _
element-ui ELEMENT

const isProduction = process.env.NODE_ENV !== 'development';

const cdn = {
    
    
    externals: {
    
    
        vue: 'Vue',
        'vue-router': 'VueRouter',
        vuex: 'Vuex',
        "element-ui": "ELEMENT"
    },
    css: [
        'https://cdn.bootcdn.net/ajax/libs/element-ui/2.15.9/theme-chalk/index.min.css',
    ],
    js: [
        'https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.min.js',
        'https://cdn.jsdelivr.net/npm/[email protected]/dist/vue-router.min.js',
        'https://cdn.jsdelivr.net/npm/[email protected]/dist/vuex.min.js',
        'https://cdn.bootcdn.net/ajax/libs/element-ui/2.15.9/index.min.js'
    ]
};

module.exports = {
    
    
    publicPath: './',
    chainWebpack: config => {
    
    
        config.when(isProduction, config => {
    
    
            config.entry('app').clear().add('./src/main-prod.ts');
            
            // 我们希望的是在生产环境下才进行cdn优化!!!这点理解很重要。
            // 告诉webpack需要排除的依赖名称和挂载在window上的对象属性名称。
            config.set('externals', cdn.externals);
            // 这里的作用是在后面index.html页面中通过link,script标签加载这些cdn链接。
            config.plugin('html').tap(args => {
    
    
                args[0].cdn = cdn;
                return args;
            });
            
        });
        config.when(!isProduction, config => {
    
    
            config.entry('app').clear().add('./src/main-dev.ts');
        });
    }
};

insert image description here

index.html

It also needs to be explained here that the location of the index.html page is generally in the public directory.
Does the following htmlWebpackPlugin.options.cdn object look familiar, isn’t it the property we added through the production environment configuration config.plugin('html') in vue.config.js? It's really a chain.

<!DOCTYPE html>
<html lang="zh">

<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>
  
  <!-- 这里从cdn配置里面加载css文件 -->
  <% for (var i in htmlWebpackPlugin.options.cdn && htmlWebpackPlugin.options.cdn.css) { %>
    <link href="<%= htmlWebpackPlugin.options.cdn.css[i] %>" rel="preload" as="style" />
    <link href="<%= htmlWebpackPlugin.options.cdn.css[i] %>" rel="stylesheet" />
  <% } %>

  <!-- 这里从cdn配置里面加载js文件 -->
  <% for (var i in htmlWebpackPlugin.options.cdn && htmlWebpackPlugin.options.cdn.js) { %>
    <link href="<%= htmlWebpackPlugin.options.cdn.js[i] %>" rel="preload" as="script" />
  <% } %>
  
</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 -->
  
  <!-- 这里从cdn配置里面加载js文件 -->
  <% for (var i in htmlWebpackPlugin.options.cdn && htmlWebpackPlugin.options.cdn.js) { %>
    <script src="<%= htmlWebpackPlugin.options.cdn.js[i] %>"></script>
  <% } %>
  
</body>

</html>

package test

After completing the above steps, the cdn packaging optimization is complete. Now run the packaging test.
Compare the packaged data below with the packaged data without CDN optimization, is the dependency ruled out? Packing times are also faster.
Did you feel more confident during the interview?

insert image description here

Guess you like

Origin blog.csdn.net/qq_34191778/article/details/126202249