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
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)
- 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)
- Make good use of alias (the new version of vue-cli has already done this)
- 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
Reference on demand
- Enable happypack multi-core build project
- Modify source-map configuration
- 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" }]] }
1.2 Then introduce components as needed to reduce the size
import { Button } from 'iview' Vue.component('Table', Table)
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')] }
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)
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
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 } }) ] }
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') })
4.3 Add command
"dll": "webpack --config ./build/webpack.dll.config.js"
in /package.json 4.4 Add DLL-based JS introduction in /index.html (must be introduced first)
<script></script>
4.5 Execute the build
npm run dll(这一步会生成build/vendor-manifest.json和static/js/vendor.dll.js) npm run dev 或 npm run build
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!

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

WebStorm Mac version
Useful JavaScript development tools

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 English version
Recommended: Win version, supports code prompts!