1. Code size optimization
- JavaScript compression :
In themode=production
case,Webpack
are automatically compressed code, we can customize your own compression tool, it recommended hereterser-webpack-plugin
, it is theWebpack
official maintenance of a plugin,terser
to compressJavaScript
the code.UglifyJS
In the compressionES5
done very good, but with theES6
popularity of syntaxUglifyJS
inES6
the code compression is not good enough, so withuglify-es
the project, but afteruglify-es
the project is not maintained,terser
fromuglify-es
a branch to pull the project to continue to maintain.terser-webpack-plugin
It has withUglifyjs-webpack-plugin
the same parameters. - to sum up:
- Reasonably divide code responsibilities, and appropriately use on-demand loading schemes;
- Make good use of
webpack-bundle-analyzer
plug-ins, to help analyze theWebpack
module after the package dependencies; - Set a reasonable
SplitChunks
packet; - For some
UI
component library, e.g.AntDesign
,ElementUI
materials may be usedbable-plugin-import
such tools are optimized; - Use
lodash、momentjs
of these libraries, do not fall into the introduction, to demand the introduction,momentjs
you can usedate-fns
the library instead; - Rational use of
hash
placeholders, to preventhash
recurring, thereby leading to changes in the file nameHTTP
cache expires; - Use
polyfill
it reasonably to prevent redundant code; - The use of
ES6
grammar, try not to use the code with side effects, in order to enhanceTree-Shaking
the effect; - Use
Webpack
of theScope Hoisting
(scope lift) function, andScope Hoisting
iswebpack
throughES6
static analysis grammar to analyze the dependencies between the modules, the modules as far as possible into the same function
- CSS compression :
cssnano
is based onpostcss
a powerful plug-in package, which integrates30
multiple plug-ins, just execute a command, it is possible for usCSS
to do many different types of optimizations, such as:
- Remove spaces and the last semicolon;
- Delete comments;
- Optimize font weight;
- Discard duplicate style rules;
- Compression selector
- Reduce handwriting attributes;
- Merger rules
- Image resource optimization:
Usually our code size is much smaller than the image size, and sometimes the code of the entire page is not as big as a header image. Fortunately, image resources will not block browser rendering, but unreasonable image size will also consume a certain amount of code. You can use:url-loader、svg-url-loader 和 image-webpack-loader
to optimize pictures, you can also use Sprite to optimize picture resources, as shown below:
url-loader
According to the configuration, static files smaller than a certain volume can be inlined into our application. When we specifylimit
thisoptions
option, it will be encoded into the file smaller than no configurationBase64
dataurl
and theurl
return, which can be linked into the picture withinJavaScript
the code, and save aHTTP
request.svg-url-loader
The working principle is similarurl-loader
, except that it usesURL encoding
rather thanBase64
for file encoding for theSVG
picture, itsvg-url-loader
's in this way that is effective, because theSVG
plain text file on the file essence, thisURL encoding
coding of scale become more pronounced.- If we project a particularly large number of small pictures, for example, there are a lot of
icon
class icon, this time it is recommended to use Sprite map(CSS Sprite)
to merge these small diagram to a large map, and then usebackground-position
to set the location of the picture, we can save many times in such a way Small picture request. - For the big picture, it can be used
image-webpack-loader
to compress images,image-webpack-loader
it supports theJPG、PNG、GIF 和 SVG
picture format, so we met all of these types of pictures will use it.
2. Enhance the cache hit rate
- Browser cache policy and
Webpack
cache configuration, use your browser's persistent caching scheme in two steps, the first step is we generally static resources will(JavaScript 、CSS、图片字体文件等)
these changes do not often find a more suitable file server storage, such as putCDN
on the server and configure a separate domain name, such as Baidu commonCDN
domain is:x.bdimg.com
andx.bdstatic.com
the domain name, the benefits of doing so are:
- Ensure the separation of dynamics and statics. Separate deployment of dynamic pages and static resources is conducive to better maintenance of services;
CDN
May be closer to the user's terminal, expedited services, you can view the detailedCDN
principles;- Resources are not static dynamic logic, a separate header page request can be reduced
Cookie
and so the field necessary to reduce theHTTP
bandwidth. - After the static resources stored in a separate server, you need to do is a reasonable allocation of
HTTP
cache-related agreements, such as we usedCache-Control
to tell the browser, the current filemax-age: Cache-Control: max-age=31536000
set above the file cache time of year(31536000=360024365)
.
-
After the completion of the first step, the second step is to rename the static resources for the change happened, so although the use of static files
CDN
and cache strong, but as long as the content changes, then the path to the file (URL) changes, the browser The browser will still request the download again: -
Therefore, cache related
Webpack
packaging optimization, the rational use ofHTTP
cache-related request header field, and matingWebpack
ofchunkhash
andcontenthash
can be done according to changes in file contents and enhanced dependence browser cache, additional code changes in accordance with reasonable frequency resolution codes can be Play the biggest role of the cache,Webpack
the split code used in the dynamic loading method andoptimization.splitChunks
.
Three, function split code
- Code Webpack split mode:
InWebpack
in a total of three ways to split the implementation code(Code Splitting)
:
entry
Configuration: a pluralityentry
implemented files;- Dynamic load (demand loading): write by actively using the code
import()
orrequire.ensure
dynamically loaded; - Extracting common code: Use
splitChunks
configured to extract the common code.
- Setting higher weights
cacheGroup
; usingtest
function for a typejs
andcss
are provided eachcacheGroup
. In addition, we can also use thetest
function to achieve a more refined matching, for example: Ignore the part of the file and so on.
Fourth, speed optimization
-
When
Webpack
, after more than a project file, the build process will become slower, this time we need to do some optimization of the means to build speed. AffectWebpack
the speed of constructing the two "big": oneloader
andplugin
build process aspects, is a compression, optimizing these two things together, you can reduce a lot of the time posted. -
Compression speed optimization:
relative to the build process, we compress relatively speaking only production package will do, and we addition to adding compressioncache
and multithreading support outside a small space can be optimized. We useterser-webpack-plugin
can open multiple threads and cache configuration time by the following:
const TerserPlugin = require('terser-webpack-plugin');
module.exports = {
optimization: {
minimizer: [
new TerserPlugin({
cache: true, // 开启缓存
parallel: true // 多线程
})
]
}
};
- From the perspective of construction speed, how to improve the packaging speed, introduce the methods to improve the speed from the two dimensions of the construction process and compression. Among them, there are few points that can be optimized from the compression perspective, and the search process can be reduced from the search process, multithreading, and multithreading. compiled ahead and caching to optimize multiple angles, which focuses on reducing the use of several search process configuration, use
thread-loader
andHappyPack
to open multi-threaded, useDLLPlugin
to compile and use of pre-babel-loader
caching methods. In the actual project, it is not necessary to optimize the construction speed. If the project is simple, it is not necessary at all, and specific problems should be analyzed in detail. In any case, keep theWebpack
latest version is a simple yet effect a good way!
、 、 Tree-Shaking
-
Tree-Shaking
Term is a front-end, intended to shake the tree means, in terms generally used to describe the front end to removeJavaScript
the code useless context, which can effectively reduce the packing volume. RegardingTree-Shaking
, theWebpack
official document has a very vivid description: you can imagine the application as a tree. The green color represents the source code sum actually usedlibrary
, which is the living leaves on the tree. Gray represents useless code, which is the withered leaves on autumn trees. In order to remove the dead leaves, you must shake the tree to make them fall. -
Tree-Shaking realization of the principle:
Tree-Shaking
the essence is the elimination of uselessJavaScript
code. Useless code elimination(Dead Code Elimination)
widely exists in traditional programming language compilers. The compiler can determine that certain codes do not affect the output at all, and then eliminate these codes. This is calledDCE(Dead Code Elimination)
.Tree-Shaking
IsDCE
a new implementationJavascript
with traditional programming languages is thatJavaScript
most cases are executed in the browser needs to be loaded via a network, and then parseJavaScript
the file and execute. -
Webpack Tree-Shaking actual codes:
inWebpack
inTree-Shaking
need with themode=production
use of, sinceWebpack
theTree-Shaking
actual points to achieve a two-step:
Webpack
To analyze their ownES6 Modules
introduction and usage, remove unusedimport
introduced;- With tools (such as
uglifyjs-webpack-plugin
andterser-webpack-plugin
) to delete, these tools are onlymode=production
to be used will be.
-
Configuration sideEffects:
Webpack
project, can bepackage.json
usedsideEffects
to tellwebpack
the code which files have side effects, so that the file can rest assured that the code has no side effects of the use ofTree-Shaking
optimization. If your project is a library or tool libraries, you need to publish to other projects use, and the use of projectES6 Modules
preparation, no side effects, then the project can bepackage.json
set upsideEffects:false
to tell use that itemwebpack
can rest assured that the projectTree-Shaking
, without having to Consider side effects. -
Tree-Shaking
It is of great significance to front-end projects, an ideal world of ultimate optimization, and another ultimate ideal of front-end evolution. But the ideal is good, the reality is skinny, really playTree-Shaking
a strong role, we also need to maintain good habits in their daily development code:
- To use the
Tree-Shaking
necessity to ensure the module references areES6
standardized, many tools library or library providesES6
syntax library, for example,lodash
theES6
versionlodash-es
; - The introduction of on-demand module, to avoid "a hook", for example, we want to use
lodash
theisNumber
can be usedimport isNumber from 'lodash-es/isNumber';
insteadimport {isNumber} from 'lodash-es';
- Reduce the side effect code in the code. Other component library, for example,
AntDesign
andElementUI
these component library, itself developed its ownBabel
plug-ins, by way of plug-in modules to introduce on-demand, to avoid the fall of the introduction of all the components.