Home Web Front-end JS Tutorial How to speed up and optimize vue-cli code

How to speed up and optimize vue-cli code

Apr 13, 2018 pm 03:49 PM
vue-cli code optimization

This time I will show you how to speed up and optimize the vue-cli code, and what are the precautions for speeding up and optimizing the vue-cli code. The following is a practical case, let's take a look.

Preface

With the globalization of Vue, various Vue component frameworks have become more and more perfect. From the early element-ui to vux, iview and other high-quality projects, using Vue for front-end construction is already an engineering task. , Modularization, Agile things

Among them, I believe many people will choose the official vue-cli initialization project template, and then develop and build it by introducing third-party component frameworks and tools. I personally highly recommend this approach. However, the project template initialized by vue-cli is for all developers after all, and there will be certain compromises in terms of compatibility. I believe many people have searched for various webpack construction optimization articles, but many of them are either too old or not rigorous

This article hopes to strike a balance between time-consuming optimization and build performance improvement, that is, spend the least time and make the least modifications to the official template to earn the maximum build performance improvement

Thoughts

In the early versions of vue-cli and webpack2, the following optimized configurations were circulated on the Internet, but in fact, the new versions of vue-cli and webpack3 no longer require

  1. Use ParallelUglifyPlugin to replace UglifyPlugin (the new version of UglifyPlugin already supports and enables multi-threaded parallel build by default, so this step is not necessary)

  2. Enable Scope Hoisting of webpack3 (the new version of vue-cli has been configured with webapck3, And this configuration has been turned on by default)

  3. Make good use of alias (the new version of vue-cli has already done this)

  4. Configure CommonsChunkPlugin to extract the public Code (the new version of vue-cli has already done this)

For the new version of vue-cli and webpack3, the following simple configuration can increase the build speed by at least 2 times after optimization

  1. Reference on demand

  2. Enable happypack multi-core build project

  3. Modify source-map configuration

  4. Enable DllPlugin and DllReferencePlugin Precompiled library files

# Practice

1. Reference on demand

1.1 Almost all third-party component frameworks will provide on-demand reference methods for components. Taking iview as an example, through the plug-in babel-plugin-import, components can be loaded on demand and the file size can be reduced. You only need to modify the .babelrc file

npm install babel-plugin-import --save-dev
// .babelrc
{
 "plugins": [["import", {
 "libraryName": "iview",
 "libraryDirectory": "src/components"
 }]]
}
Copy after login

1.2 Then introduce components as needed to reduce the size

import { Button } from 'iview'
Vue.component('Table', Table)
Copy after login

2. Enable happypack multi-core build project

After installing happypack, modify the /build/webpack.base.conf.js file

npm install happypack --save-dev
// /build/webpack.base.conf.js
const HappyPack = require('happypack')
const os = require('os')
const happyThreadPool = HappyPack.ThreadPool({ size: os.cpus().length })
// 增加HappyPack插件
plugins: [
 new HappyPack({
  id: 'happy-babel-js',
  loaders: ['babel-loader?cacheDirectory=true'],
  threadPool: happyThreadPool,
 })
 ]
// 修改引入loader
{
 test: /\.js$/,
 // loader: 'babel-loader',
 loader: 'happypack/loader?id=happy-babel-js', // 增加新的HappyPack构建loader
 include: [resolve('src'), resolve('test')]
}
Copy after login

3. Modify source-map configuration

3.1 First modify the /config/index.js file

// /config/index.js
dev环境:devtool: 'eval'(最快速度)
prod环境:productionSourceMap: false(关闭source-map)
Copy after login

3.2 Then modify the /src/main.js file and turn off the debugging information of the production environment

// /src/main.js
const isDebug_mode = process.env.NODE_ENV !== 'production'
Vue.config.debug = isDebug_mode
Vue.config.devtools = isDebug_mode
Vue.config.productionTip = isDebug_mode
Copy after login

4. Enable DllPlugin and DllReferencePlugin precompiled library files

This is the most complicated step and the most obvious step to improve the effect. The principle is to compile and package the third-party library files separately once. There is no need to compile and package the third-party libraries in subsequent builds

4.1 Add the build/webpack.dll.config.js file and configure the modules that need to be DLLed separately

const path = require("path")
const webpack = require("webpack")
module.exports = {
 // 你想要打包的模块的数组
 entry: {
  vendor: ['vue/dist/vue.esm.js', 'axios', 'vue-router', 'iview']
 },
 output: {
  path: path.join(dirname, '../static/js'), // 打包后文件输出的位置
  filename: '[name].dll.js',
  library: '[name]_library'
 },
 plugins: [
  new webpack.DllPlugin({
   path: path.join(dirname, '.', '[name]-manifest.json'),
   name: '[name]_library',
   context: dirname
  }),
  // 压缩打包的文件
  new webpack.optimize.UglifyJsPlugin({
   compress: {
    warnings: false
   }
  })
 ]
}
Copy after login

4.2 Add the following plug-ins to build/webpack.dev.conf.js and build/webpack.prod.conf.js

new webpack.DllReferencePlugin({
  context: dirname,
  manifest: require('./vendor-manifest.json')
})
Copy after login

4.3 Add command

"dll": "webpack --config ./build/webpack.dll.config.js"
Copy after login

in /package.json 4.4 Add DLL-based JS introduction in /index.html (must be introduced first)

<script src="/static/js/vendor.dll.js"></script>
Copy after login

4.5 Execute the build

npm run dll(这一步会生成build/vendor-manifest.json和static/js/vendor.dll.js)
npm run dev 或 npm run build
Copy after login

Postscript

After the above four major steps are completed, we have completed the optimization and improvement of the vue-cli template project construction. Although it still seems not simple, this is already the simplest optimization, and there are more tricks and tricks. Coincidentally, I didn’t expand it because I think too much optimization configuration is of little significance, but will bring too much redundancy and complexity to the project

The actual test build effect of the above configuration was reduced from the original 13 seconds to about 6 seconds, and the hot deployment was even millisecond-level

The most important thing is that the simplest configuration can be easily reconfigured and used after vue-cli and webpack are upgraded to new versions in the future. After a proficient configuration, it only takes about 5 minutes to restore the configuration. Think about it. Just modifying the configuration in 5 minutes can increase the speed of each build by more than 2 times. Aren’t you a little excited? :)

Let me say a few more words here. In fact, the upgrade from webpack2 to webpack3 is quite disappointing to me, because it still does not fundamentally solve the problem of overly complex configuration. As a product built with the goal of occupying all web projects in the world, It should be considered more from the perspective of ease of use/humanity

Every time I look at the various .babelrc, .postcssrc.js... and various .confs in the webpack project files, and even various main, index, and app files. I can’t help but want to complain about why the front-end construction has developed like this. In a good project, there are more than a dozen configuration files , is it really necessary? I originally thought that webpack3 would make all this simple, but it did not. But since there is no way to change it for the time being, what we can do is to understand the principles as much as possible and try our best to simplify/optimize ​​​​​​​​

I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!

Recommended reading:

HTML JS implements a rolling digital clock

How to use VueRouter’s navigation guard

Detailed explanation of the steps for implementing table paging using vue element                      

The above is the detailed content of How to speed up and optimize vue-cli 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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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)

Discussion on Golang's gc optimization strategy Discussion on Golang's gc optimization strategy Mar 06, 2024 pm 02:39 PM

Golang's garbage collection (GC) has always been a hot topic among developers. As a fast programming language, Golang's built-in garbage collector can manage memory very well, but as the size of the program increases, some performance problems sometimes occur. This article will explore Golang’s GC optimization strategies and provide some specific code examples. Garbage collection in Golang Golang's garbage collector is based on concurrent mark-sweep (concurrentmark-s

In-depth interpretation: Why is Laravel as slow as a snail? In-depth interpretation: Why is Laravel as slow as a snail? Mar 07, 2024 am 09:54 AM

Laravel is a popular PHP development framework, but it is sometimes criticized for being as slow as a snail. What exactly causes Laravel's unsatisfactory speed? This article will provide an in-depth explanation of the reasons why Laravel is as slow as a snail from multiple aspects, and combine it with specific code examples to help readers gain a deeper understanding of this problem. 1. ORM query performance issues In Laravel, ORM (Object Relational Mapping) is a very powerful feature that allows

Tsinghua University and Zhipu AI open source GLM-4: launching a new revolution in natural language processing Tsinghua University and Zhipu AI open source GLM-4: launching a new revolution in natural language processing Jun 12, 2024 pm 08:38 PM

Since the launch of ChatGLM-6B on March 14, 2023, the GLM series models have received widespread attention and recognition. Especially after ChatGLM3-6B was open sourced, developers are full of expectations for the fourth-generation model launched by Zhipu AI. This expectation has finally been fully satisfied with the release of GLM-4-9B. The birth of GLM-4-9B In order to give small models (10B and below) more powerful capabilities, the GLM technical team launched this new fourth-generation GLM series open source model: GLM-4-9B after nearly half a year of exploration. This model greatly compresses the model size while ensuring accuracy, and has faster inference speed and higher efficiency. The GLM technical team’s exploration has not

C++ program optimization: time complexity reduction techniques C++ program optimization: time complexity reduction techniques Jun 01, 2024 am 11:19 AM

Time complexity measures the execution time of an algorithm relative to the size of the input. Tips for reducing the time complexity of C++ programs include: choosing appropriate containers (such as vector, list) to optimize data storage and management. Utilize efficient algorithms such as quick sort to reduce computation time. Eliminate multiple operations to reduce double counting. Use conditional branches to avoid unnecessary calculations. Optimize linear search by using faster algorithms such as binary search.

Decoding Laravel performance bottlenecks: Optimization techniques fully revealed! Decoding Laravel performance bottlenecks: Optimization techniques fully revealed! Mar 06, 2024 pm 02:33 PM

Decoding Laravel performance bottlenecks: Optimization techniques fully revealed! Laravel, as a popular PHP framework, provides developers with rich functions and a convenient development experience. However, as the size of the project increases and the number of visits increases, we may face the challenge of performance bottlenecks. This article will delve into Laravel performance optimization techniques to help developers discover and solve potential performance problems. 1. Database query optimization using Eloquent delayed loading When using Eloquent to query the database, avoid

Create and run Linux ".a" files Create and run Linux ".a" files Mar 20, 2024 pm 04:46 PM

Working with files in the Linux operating system requires the use of various commands and techniques that enable developers to efficiently create and execute files, code, programs, scripts, and other things. In the Linux environment, files with the extension &quot;.a&quot; have great importance as static libraries. These libraries play an important role in software development, allowing developers to efficiently manage and share common functionality across multiple programs. For effective software development in a Linux environment, it is crucial to understand how to create and run &quot;.a&quot; files. This article will introduce how to comprehensively install and configure the Linux &quot;.a&quot; file. Let's explore the definition, purpose, structure, and methods of creating and executing the Linux &quot;.a&quot; file. What is L

Create Agent in one sentence! Robin Li: The era is coming when everyone is a developer Create Agent in one sentence! Robin Li: The era is coming when everyone is a developer Apr 17, 2024 pm 02:28 PM

The big model subverts everything, and finally got to the head of this editor. It is also an Agent that was created in just one sentence. Like this, give him an article, and in less than 1 second, fresh title suggestions will come out. Compared to me, this efficiency can only be said to be as fast as lightning and as slow as a sloth... What's even more incredible is that creating this Agent really only takes a few minutes. Prompt belongs to Aunt Jiang: And if you also want to experience this subversive feeling, now, based on the new Wenxin intelligent agent platform launched by Baidu, everyone can create their own intelligent assistant for free. You can use search engines, smart hardware platforms, speech recognition, maps, cars and other Baidu mobile ecological channels to let more people use your creativity! Robin Li himself

Laravel performance bottleneck revealed: optimization solution revealed! Laravel performance bottleneck revealed: optimization solution revealed! Mar 07, 2024 pm 01:30 PM

Laravel performance bottleneck revealed: optimization solution revealed! With the development of Internet technology, the performance optimization of websites and applications has become increasingly important. As a popular PHP framework, Laravel may face performance bottlenecks during the development process. This article will explore the performance problems that Laravel applications may encounter, and provide some optimization solutions and specific code examples so that developers can better solve these problems. 1. Database query optimization Database query is one of the common performance bottlenecks in Web applications. exist

See all articles