Table of Contents
1 ) The webpack configuration error caused the library to be repeatedly compiled into a file
2) Caused by too large third-party files
3) The js module does not load on demand
1) Vue’s own asynchronous method
2) Import() of es proposal
3) require.ensure() provided by webpack
Home Web Front-end Vue.js A brief analysis of web front-end project optimization in Vue (with code)

A brief analysis of web front-end project optimization in Vue (with code)

Aug 27, 2021 am 09:39 AM
vue.js

In the previous article "Teach you step-by-step how to use JS to write universal modules (detailed code explanation)", I introduced how to use JS to write universal modules. The following article will give you an understanding of web front-end project optimization in Vue. Friends in need can refer to it. I hope it will be helpful to you.

A brief analysis of web front-end project optimization in Vue (with code)

I finally got free time today, and I want to optimize the kui documentation project. It's too slow to open. It takes a few seconds for http://k-ui.cn

to be fully displayed. I can't stand it. If you look at the picture, you will understand

A brief analysis of web front-end project optimization in Vue (with code)

There is nothing surprising when you see this, why it is so slow.

Because the webpack configuration in the documentation is uselessvue-cli scaffolding, I configured it manually, so I guess there will be more problems

1 ) The webpack configuration error caused the library to be repeatedly compiled into a file

I gradually checked the relatively large files after compilation and found that index.js is the entry file, and its content includes the vue library that has been repeatedly packaged. As shown below

A brief analysis of web front-end project optimization in Vue (with code)

Troubleshooting the webpack configuration step by step, no problem is found, so where is the problem? I searchedvue was introduced, and it was found that 3 files were imported vue, but this did not affect the duplication of compilation. It shouldn’t be. Finally, the problem was discovered, because it was mac Due to the case sensitivity of the environment, "import Vue from 'vue'" was written as "import Vue from 'Vue'" with a shake of the hand.

There seems to be no problemdebugThere will be no errors in debugging. But the problem arises here. The problem is solved by changing the "Vue" after from to lowercase "vue". After recompilation the file is over 130 kb smaller. From 945kb to over 800kb, keep optimizing.

2) Caused by too large third-party files

Because some parts of the documentation require code highlighting, the highlight.js code highlighting library is used in this article. I wrote a component by myself, the code is as follows:

<!-- code.vue -->
<template>
  <div v-high class="k-code">
    <pre: style="styles" ref="rel">
      <code: class="lang">
        <slot> </slot>
      </code>
    
Copy after login
//code.js
import Hljs from "highlight.js";
import "highlight.js/styles/atom-one-light.css";
const vueHljs = {};
vueHljs.install = (Vue) => {
  Vue.directive("high", function (el, binding) {
    let blocks = el.querySelectorAll("pre code");
    Array.prototype.forEach.call(blocks, Hljs.highlightBlock);
  });
};
export default vueHljs;
Copy after login
<!-- 调用 -->
<code lang="xml html">
  {{ code }}
</code>
Copy after login

In fact, there will be no problem if the code is written like this, but why is the file so big after compilation, 800 is more than kb, so... I commented out the key code highlighting code, which is where highlight.js was introduced. Compile again:

The compiled file is only 130kb, and we have found the source of the problem.

I used Google's code highlighting before, but I don't need it this time, and markdown don't want to bother with it either.

Go to node_modules and explore carefully. Because code highlighting contains too many languages ​​​​and syntax, I compile it every time and it is a full package, python,sql, c , etc.50 are all in several highlighted languages, but I only need js and html syntax Highlight, so I put forward what I want from the library:

var Hljs = require("./highlight");
//只要这2个高亮语言库,其他干掉
Hljs.registerLanguage("xml", require("./lang/xml"));
Hljs.registerLanguage("javascript", require("./lang/javascript"));
Copy after login

Compile again, after compilation 180kb is still within the acceptable range.

3) The js module does not load on demand

because vue is a single page web, driven by router view, as the project becomes larger and larger, it is necessary to load this on demand, otherwise all pages will be packaged in the same js file. Causing slow loading.

On-demand loading (that is, lazy loading) has 3 implementation methods

1) Vue’s own asynchronous method

in Just make modifications when router push

{
  path: &#39;/test&#39;,
  name: &#39;test&#39;,
  component: resolve => require([&#39;../components/test&#39;], resolve)
}
Copy after login

2) Import() of es proposal

Official document

Pay attention to the content and name The same will be packaged into a file

const test = () => import( /* webpackChunkName: "test" */ &#39;../components/test&#39;) {
    path: &#39;/test&#39;,
    name: &#39;test&#39;,
    component: test
  },
Copy after login

3) require.ensure() provided by webpack

Note that ensure passes parameters, the last chunkname, and the output configuration is not passed chunkFilename: will be [id].build.js

{
  path: &#39;/test&#39;,
  name: &#39;test&#39;,
  component: resolve => require.ensure([], () => resolve(require(&#39;../components/test&#39;)), &#39;test&#39;)
},
Copy after login

Note: require.ensure() is unique to webpack and has been replaced by import().

The above 3 methods can achieve on-demand loading, and finally configure chunkFilename<div class="code" style="position:relative; padding:0px; margin:0px;"><pre class='brush:php;toolbar:false;'>output: { path: path.resolve(__dirname, &amp;#39;../dist&amp;#39;), filename: &amp;#39;js/[name].js&amp;#39;, //.[hash].js&amp;#39;, publicPath: &amp;#39;/&amp;#39;, chunkFilename: &amp;#39;js/[name].[chunkhash:3].js&amp;#39;, },</pre><div class="contentsignin">Copy after login</div></div># in webpack config

##Of course, I did on-demand loading in the project, but the final packaged files were still merged. Then let’s see where the problem lies.

My routing works like this:

import Vue from "vue";
import Router from "vue-router";

Vue.use(Router);

let routes = [];

let r = [
  "",
  "install",
  "start",
  "log",
  "input",
  "button",
  "select",
  "switch",
  "form",
  "colorpicker",
  "loading",
  "icon",
  "timeline",
  "theme",
  "react-kui",
  "angular-kui",
  "alert",
  "message",
  "notice",
  "upload",
  "poptip",
  "menu",
  "tabs",
  "badge",
  "checkbox",
  "radio",
  "datepicker",
  "table",
  "layout",
  "page",
  "modal",
  "kyui-loader",
  "sponsor",
  "about",
];

r.forEach((x) => {
  routes.push({
    path: `/${x}`,
    component: (resolve) =>
      require([x == "" ? "./ui/index" : `./ui/${x}`], resolve),
    // component: r => require.ensure([], () => r(require(x==&#39;&#39;?&#39;/ui/index&#39;: `./ui/${x}` )), x)
  });
});

let routers = new Router({
  routes: routes,
  mode: "history",
});
export default routers;
Copy after login

There seems to be no problem with on-demand loading, but the finally packaged

chunkFilename has 300kb, and all pages are typed into a js file.

探究了一番,因为是异步加载,所以不能动态传值的,map遍历的时候路径组合x值是动态传入,导致打包后无法识别。最后修改为静态的,问题解决了。重新编译后多个页面路由分割成单个js文件,每个约10kb左右,路由改变时,动态加载对应的js文件

import xx from &#39;/dev/test‘   //这里的abc 是静态的值 如 ‘/ui/abc.vue’ {

path: &#39;xx&#39;,
  component: xx
}
Copy after login

至此,问题解决了,页面加载正常情况下延时1-2秒,时间缩短了将近10陪。

【完】

推荐学习:vue.js高级教程

The above is the detailed content of A brief analysis of web front-end project optimization in Vue (with code). For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

In-depth discussion of how vite parses .env files In-depth discussion of how vite parses .env files Jan 24, 2023 am 05:30 AM

When using the Vue framework to develop front-end projects, we will deploy multiple environments when deploying. Often the interface domain names called by development, testing and online environments are different. How can we make the distinction? That is using environment variables and patterns.

What is the difference between componentization and modularization in vue What is the difference between componentization and modularization in vue Dec 15, 2022 pm 12:54 PM

The difference between componentization and modularization: Modularization is divided from the perspective of code logic; it facilitates code layered development and ensures that the functions of each functional module are consistent. Componentization is planning from the perspective of UI interface; componentization of the front end facilitates the reuse of UI components.

Detailed graphic explanation of how to integrate the Ace code editor in a Vue project Detailed graphic explanation of how to integrate the Ace code editor in a Vue project Apr 24, 2023 am 10:52 AM

Ace is an embeddable code editor written in JavaScript. It matches the functionality and performance of native editors like Sublime, Vim, and TextMate. It can be easily embedded into any web page and JavaScript application. Ace is maintained as the main editor for the Cloud9 IDE and is the successor to the Mozilla Skywriter (Bespin) project.

Let's talk in depth about reactive() in vue3 Let's talk in depth about reactive() in vue3 Jan 06, 2023 pm 09:21 PM

Foreword: In the development of vue3, reactive provides a method to implement responsive data. This is a frequently used API in daily development. In this article, the author will explore its internal operating mechanism.

Explore how to write unit tests in Vue3 Explore how to write unit tests in Vue3 Apr 25, 2023 pm 07:41 PM

Vue.js has become a very popular framework in front-end development today. As Vue.js continues to evolve, unit testing is becoming more and more important. Today we’ll explore how to write unit tests in Vue.js 3 and provide some best practices and common problems and solutions.

A simple comparison of JSX syntax and template syntax in Vue (analysis of advantages and disadvantages) A simple comparison of JSX syntax and template syntax in Vue (analysis of advantages and disadvantages) Mar 23, 2023 pm 07:53 PM

In Vue.js, developers can use two different syntaxes to create user interfaces: JSX syntax and template syntax. Both syntaxes have their own advantages and disadvantages. Let’s discuss their differences, advantages and disadvantages.

A brief analysis of how to handle exceptions in Vue3 dynamic components A brief analysis of how to handle exceptions in Vue3 dynamic components Dec 02, 2022 pm 09:11 PM

How to handle exceptions in Vue3 dynamic components? The following article will talk about Vue3 dynamic component exception handling methods. I hope it will be helpful to everyone!

A brief analysis of how vue implements file slicing upload A brief analysis of how vue implements file slicing upload Mar 24, 2023 pm 07:40 PM

In the actual development project process, sometimes it is necessary to upload relatively large files, and then the upload will be relatively slow, so the background may require the front-end to upload file slices. It is very simple. For example, 1 A gigabyte file stream is cut into several small file streams, and then the interface is requested to deliver the small file streams respectively.

See all articles