Detailed example of vue-cli optimized webpack configuration
The recent project has passed the busy infrastructure construction period, and it has gradually relaxed. I am going to record my recent webpack optimization measures, hoping to have the effect of reviewing the past and learning the new. This article mainly introduces the detailed explanation of webpack configuration based on vue-cli optimization. The editor thinks it is quite good, so I will share it with you now and give it as a reference. Let’s follow the editor to take a look, I hope it can help everyone.
The project uses vue family bucket, and the build configuration is improved based on vue-cli. Regarding the original webpack configuration, you can read this article vue-cli#2.0 webpack configuration analysis. The article basically explains each line of code in the file in detail, which will help you better understand webpack.
After carefully summarizing, my optimization is basically based on the points circulated on the Internet
-
Extract common libraries through externals configuration and quote cdn
Configure CommonsChunkPlugin properly
Make good use of alias
dllplugin enables pre-compilation
happypack multi-core build project
externals
Document address https://doc.webpack-china.org /configuration/externals/
Prevent certain imported packages from being packaged into bundles, and instead obtain these external dependencies from the outside during runtime.
CommonsChunkPlugin
Document address https://doc.webpack-china.org/plugins/commons-chunk-plugin/
The CommonsChunkPlugin plug-in is an optional function for creating an independent file (also called a chunk). This file includes common modules of multiple entry chunks. By separating the common modules, the final synthesized file can be loaded once at the beginning and then stored in the cache for subsequent use. This brings speed improvements because the browser will quickly pull the common code out of the cache instead of loading a larger file every time a new page is accessed.
resolve.alias
Document address https://doc.webpack-china.org/configuration/resolve/#resolve-alias
Create import or require aliases to ensure that module introduction becomes easier. For example, some common modules located in the src/ folder:
However, through my own practice, the last three points are the most optimized for my own project. The article also mainly explains the following points in detail
The original time required to package a project is basically about 40 seconds, then how long will it take to go through the next three steps of optimization
1. Use dllplugin to precompile and reference
Why should we reference Dll in the first place? After browsing some articles on the Internet, I found that in addition to speeding up the build, using webpack's dll has another benefit.
Dll exists independently after being packaged. As long as the libraries it contains are not increased, decreased, or upgraded, the hash will not change, so the online dll code does not need to be updated frequently with version releases. Because Dll packages are basically independent library files, one characteristic of such files is that they do not change much. When we normally package these library files into an app.js, changes in other business files affect the cache's optimization of the build, resulting in the need to search for relevant files in the npm package again every time. After using DLL, as long as the included libraries are not upgraded, added or deleted, there is no need to repackage. This also improves build speed.
So how to use Dll to optimize the project?
First, you must create a dll configuration file and introduce the third-party libraries required by the project. The characteristic of this type of library is that it does not need to be updated frequently with version releases and is stable in the long term.
const webpack = require('webpack'); const path = require('path'); module.exports = { entry: { //你需要引入的第三方库文件 vendor: ['vue','vuex','vue-router','element-ui','axios','echarts/lib/echarts','echarts/lib/chart/bar','echarts/lib/chart/line','echarts/lib/chart/pie', 'echarts/lib/component/tooltip','echarts/lib/component/title','echarts/lib/component/legend','echarts/lib/component/dataZoom','echarts/lib/component/toolbox'], }, output: { path: path.join(__dirname, 'dist-[hash]'), filename: '[name].js', library: '[name]', }, plugins: [ new webpack.DllPlugin({ path: path.join(__dirname, 'dll', '[name]-manifest.json'), filename: '[name].js', name: '[name]', }), ] };
The basic configuration parameters are basically the same as webpack. I believe everyone who has seen optimization will understand what it means, so I won’t explain it. Then execute the code to compile the file. (My configuration file is placed in the build, and the path below needs to be changed according to the project path)
webpack -p --progress --config build/webpack.dll.config.js
When the execution is completed, two new files will be generated in the same directory. level, one is verdor.js generated in the dist folder, which contains the compressed code of the entry dependencies; the other is verdor-manifest.json in the dll folder, which indexes each library by number and uses It's id instead of name.
Next, you just need to add a line of code to the plugin in your webpack configuration file and it will be ok.
const manifest = require('./dll/vendor-manifest.json'); ... ..., plugin:[ new webpack.DllReferencePlugin({ context: __dirname, manifest, }), ]
At this time, if you execute the webpack command again, you can find that the time has dropped sharply from 40 seconds to about 20s. Is it twice as fast? (I don’t know if it’s because This happens because I have too many dependent libraries, so I cover my face manually).
2.happypack multi-threaded compilation
Generally node.js performs compilation in a single thread, while happypack starts multi-threading of node for construction, which greatly improves the construction speed. speed. The method of use is also relatively simple. Taking my project as an example, create a new happypack process in the plug-in, and then replace the place where the loader is used with the corresponding id
var HappyPack = require('happypack'); ... ... modules:{ rules : [ ... { test: /\.js$/, loader:[ 'happypack/loader?id=happybabel'], include: [resolve('src')] }, ... ] }, ... ... plugin:[ //happypack对对 url-loader,vue-loader 和 file-loader 支持度有限,会有报错,有坑。。。 new HappyPack({ id: 'happybabel', loaders: ['babel-loader'], threads: 4,//HappyPack 使用多少子进程来进行编译 }), new HappyPack({ id: 'scss', threads: 4, loaders: [ 'style-loader', 'css-loader', 'sass-loader', ], }) ]
这时候再去执行编译webpack的代码,打印出来的console则变成了另外一种提示。而编译时间大概从20s优化到了15s左右(感觉好像没有网上说的那么大,不知道是不是因为本身js比重占据太大的缘故)。
3.善用alias
3.配合resolve,善用alias
本来是没有第三点的,只不过在搜索网上webpack优化相关文章的时候,看到用人提到把引入文件改成库提供的文件(原理我理解其实就是1.先通过resolve指定文件寻找位置,减小搜索范围;2.直接根据alias找到库提供的文件位置)。
vue-cli配置文件中提示也有提到这一点,就是下面这段代码
resolve: { //自动扩展文件后缀名,意味着我们require模块可以省略不写后缀名 extensions: ['.js', '.vue', '.json'], //模块别名定义,方便后续直接引用别名,无须多写长长的地址 alias: { 'vue$': 'vue/dist/vue.esm.js',//就是这行代码,提供你直接引用文件 '@': resolve('src'), } },
然后我将其他所有地方关于vue的引用都替换成了vue$之后,比如
// import 'vue'; import 'vue/dist/vue.esm.js';
时间竟然到了12s,也是把我吓了一跳。。。
然后我就把jquery,axios,vuex等等全部给替换掉了。。。大概优化到了9s左右,美滋滋,O(∩_∩)O~~
4.webpack3升级
本来是没第四点,刚刚看到公众号推出来一篇文章讲到升级到webpack3的一些新优点,比如Scope Hoisting(webpack2升级到webpack3基本上没有太大问题)。通过添加一个新的插件
// 2017-08-13配合最新升级的webpack3提供的新功能,可以使压缩的代码更小,运行更快 ... plugin : [ new webpack.optimize.ModuleConcatenationPlugin(), ]
不过在添加这行代码之后,构建时间并没有太大变化,不过运行效率没试过,不知道新的效果怎么样
好了基本上感觉就是以上这些效果对项目的优化最大,虽然没有到网上说的那种只要3~4秒时间那么变态,不过感觉基本8,9秒的时间也可以了。
相关推荐:
The above is the detailed content of Detailed example of vue-cli optimized webpack configuration. For more information, please follow other related articles on the PHP Chinese website!

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

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Vue is an excellent JavaScript framework that can help us quickly build interactive and efficient web applications. Vue3 is the latest version of Vue, which introduces many new features and functionality. Webpack is currently one of the most popular JavaScript module packagers and build tools, which can help us manage various resources in our projects. This article will introduce how to use Webpack to package and build Vue3 applications. 1. Install Webpack

Introduction to Caddy Caddy is a powerful and highly scalable web server that currently has 38K+ stars on Github. Caddy is written in Go language and can be used for static resource hosting and reverse proxy. Caddy has the following main features: Compared with the complex configuration of Nginx, its original Caddyfile configuration is very simple; it can dynamically modify the configuration through the AdminAPI it provides; it supports automated HTTPS configuration by default, and can automatically apply for HTTPS certificates and configure it; it can be expanded to data Tens of thousands of sites; can be executed anywhere with no additional dependencies; written in Go language, memory safety is more guaranteed. First of all, we install it directly in CentO

Form validation is a very important link in web application development. It can check the validity of the data before submitting the form data to avoid security vulnerabilities and data errors in the application. Form validation for web applications can be easily implemented using Golang. This article will introduce how to use Golang to implement form validation for web applications. 1. Basic elements of form validation Before introducing how to implement form validation, we need to know what the basic elements of form validation are. Form elements: form elements are

Using Jetty7 for Web Server Processing in JavaAPI Development With the development of the Internet, the Web server has become the core part of application development and is also the focus of many enterprises. In order to meet the growing business needs, many developers choose to use Jetty for web server development, and its flexibility and scalability are widely recognized. This article will introduce how to use Jetty7 in JavaAPI development for We

First of all, you will have a doubt, what is frp? Simply put, frp is an intranet penetration tool. After configuring the client, you can access the intranet through the server. Now my server has used nginx as the website, and there is only one port 80. So what should I do if the FRP server also wants to use port 80? After querying, this can be achieved by using nginx's reverse proxy. To add: frps is the server, frpc is the client. Step 1: Modify the nginx.conf configuration file in the server and add the following parameters to http{} in nginx.conf, server{listen80

Face-blocking barrage means that a large number of barrages float by without blocking the person in the video, making it look like they are floating from behind the person. Machine learning has been popular for several years, but many people don’t know that these capabilities can also be run in browsers. This article introduces the practical optimization process in video barrages. At the end of the article, it lists some applicable scenarios for this solution, hoping to open it up. Some ideas. mediapipeDemo (https://google.github.io/mediapipe/) demonstrates the mainstream implementation principle of face-blocking barrage on-demand up upload. The server background calculation extracts the portrait area in the video screen, and converts it into svg storage while the client plays the video. Download svg from the server and combine it with barrage, portrait

Web standards are a set of specifications and guidelines developed by W3C and other related organizations. It includes standardization of HTML, CSS, JavaScript, DOM, Web accessibility and performance optimization. By following these standards, the compatibility of pages can be improved. , accessibility, maintainability and performance. The goal of web standards is to enable web content to be displayed and interacted consistently on different platforms, browsers and devices, providing better user experience and development efficiency.

Cockpit is a web-based graphical interface for Linux servers. It is mainly intended to make managing Linux servers easier for new/expert users. In this article, we will discuss Cockpit access modes and how to switch administrative access to Cockpit from CockpitWebUI. Content Topics: Cockpit Entry Modes Finding the Current Cockpit Access Mode Enable Administrative Access for Cockpit from CockpitWebUI Disabling Administrative Access for Cockpit from CockpitWebUI Conclusion Cockpit Entry Modes The cockpit has two access modes: Restricted Access: This is the default for the cockpit access mode. In this access mode you cannot access the web user from the cockpit
