Talking about today's thriving front-end circle, not only have all kinds of frameworks blossom, such as, and so on, in Vue
React
terms of Angular
packaging tools, development is in full swing, schools of contention, from the early king, Browserify
to the Grunt
later won the throne Gulp
, and the unique fis3
, as well as the next generation of packaging artifacts Rollup
; You can get a glimpse of some of the contrasts in browserify,grunt,gulp,rollup,webpack. In this article to explore is the current packaging tools absolute bully Webpack
.
Webpack Package Optimization
Webpack
, the current major mainstream framework of the default package, how to use it, has a more complete Chinese and English documents, and the mainstream framework also has a corresponding CLI
to the basic configuration, it is not as a discussion category. From the product layer, how to make the package to build a small volume, running fast, it is necessary to constantly explore the practice, refining and upgrading, so that the best. In this paper, we will discuss the optimization of packaging volume from the following aspects Webpack
(note: Webpack
Practice version: 3.3.0
):
The reason for locating webpack large
It is recommended to use the Webpack-bundle-analyzer--webpack plugin and the CLI utility, and she can show the content bundle as an intuitive tree that is easy to interact with, so that you can understand what is actually introduced in the package you are building; Find the untimely presence and then optimize it. We can inject the following command into the project's Package.json file to make it easier to run her ( npm run analyz
), which opens http://127.0.0.1:8888 as a display by default.
"Analyz": "Node_env=production npm_config_report=true npm Run Build"
Webpack-bundle-analyzer
Of course, the same type of Webpack-chart and Webpack-analyse, these two sites are also visual representation of the structure of the components, you can clearly see the components of the module, but the more troublesome is that you need to run the following command, generate tool analysis required JSON File:
1 2 3 4
|
Webpack--profile--json > Stats.json
If you run the specified weboack file, this command is available Webpack--config build/webpackprod conf. js--profile--json > Stats.json
|
Introduction of Dllplugin and Dllreferenceplugin
Dllplugin and Dllreferenceplugin provide a way to split packages in a way that dramatically improves build time performance. The principle is that the specific third-party NPM package module is built in advance, and then introduced through the page. This not only enables the vendor file to be greatly reduced, but also greatly improves the component speed. In view of space, the specific usage can be found in: Webpack.dll.conf.js.
External Introduction Module (CDN)
Today's front-end development, naturally using ES6
even higher versions, will be more hi. However, due to browser compatibility issues, you still have to use the Babel conversion. And this babel-polyfill
has to be introduced to ensure compatibility, as well as in the project development commonly used moment
, and lodash
so on, are very large existence, if it must be introduced, that is, consider the external introduction, and then externals
by the designation, Webpack can be processed to not participate in the packaging, It can still be accessed in code in the form of CMD, AMD, or Window/global.
1 2 3 4 5 6 7 8 9 10
|
//webpack to be specified externals: { //' vue ': ' Vue ', //' Lodash ': ' _ ', ' Babel-polyfill ': ' window ' Span class= "line", // <script src= "//cdn.bootcss.com/autotrack/2.4.1/autotrack.js" >< span class= "xml" ></SCRIPT> <script Src= "//cdn.bootcss.com/babel-polyfill/7.0.0-alpha.15/polyfill.min.js" > </SCRIPT> |
To add externals
: Key is the package name of require, and value is a global variable.
The necessity of introducing each third package "value-for-something"
The development of the front-end to today's time, if the project adopted a MVVM
model framework, data two-way binding, then like jQuery
such a library, can not say that there is no need to introduce the slightest, at least, it is not really introduced. For this, if there are some concerns, you can refer to might not need JQUERY, with the original write a few lines of code can solve the matter, it is not easy to introduce such a monster, add annoyance.
Avoid class libraries from being cited without
If this happens, the bulk of the package is not only large but also deficient. Once the project is large, it is difficult to ensure that each introduced class library is useful, especially two development. So the use of tools is very necessary, strongly recommend classes such as such Eslint
tools, and injection of the corresponding rules, the declaration is not used in the code, give a mandatory reminder, not only can effectively avoid similar situations (also applicable to the detection of common variables), but also to make the team code style, as far as possible to maintain similar , to know that the code is enough to obey the rules, but also to let the compression tool more efficient compression code, a he le?
Use modular introduction as much as possible
If jQuery
it is true that it is not introduced, many will agree, but for such lodash
tools of dependency, not everyone will build a wheel. However, all-inclusive introduction of 400KB volume, can you make your heart tremble? Fortunately, it lodash
provides a modular approach to introduction, which can be introduced on demand, fast and fast:
1 2 3 4 5 6 7 |
import {debounce} from ' Lodash ' import {throttle} from ' Lodash ' //changed to the following wording Span class= "line", import debounce from ' lodash/debounce ' import throttle from ' lodash/throttle ' |
Lazy as your good programmer, do you also find it quite troublesome to write this? So congratulations, this problem has been solved, the existence of Lodash-webpack-plugin and Babel-plugin-lodash (combined use), that is to solve the problem. It can automatically turn the full path reference into lodash
modularization by using the introduction (see example below), and the required configuration is very simple, do not repeat this (warm tip: when involved in some special methods, still need some attention).
1 2 3 4
|
Introduction of components, automatic conversion ' Lodash ' _.debounce () _.throttle ()
|
Additional is that, even if the use of the wording, or is not fast enough, each use of the file, write the import, it is much inconvenient. It is preferable to introduce the methods required by the project uniformly, add them on demand, build the local Lodash class library, and export to the framework layer (for example Vue.prototype
) for global use; see also: Vue-modular-import-lodash.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
|
Under the helper folder Lodash, unify the methods you need Import _ From' Lodash '
Export Default { Clonedeep: _. Clonedeep, Debounce: _. Debounce, Throttle: _. Throttle, Size: _. Size, Pick: _. Pick, IsEmpty: _.isempty }
Injected into the global Import _ from ' @helper/lodash.js ' Vue. Prototype.$_ = _
Application in Vue components This.$_.debounce ()
|
Introduce more appropriate packages as much as possible
As a front-end developer, you must know that there is a Momentjs presence (Parse, validate, manipulate, and display dates in JavaScript); More than that, you must know that it works well, but its posture is very plump ( Abundance), did not read this, whether there is the urge to re-build the wheel? Spacetime:a lightweight to manipulate, traverse, compare, and format dates and times across planet Earth. A monent
new class library with similar APIs, with a relatively small volume (of course, it is observed to be slightly less flexible); Date-fns: Modern JavaScript Date Utility library (modern JavaScript Day utility library), such as lodash
, you can support modularity; how do you choose to know these or more?
Load modules asynchronously on demand
On the front-end development optimization, it is important to merge requests and resources as much as possible, such as the common request data Merge, compression merge JS, the construction sprite map of this and so on (of course, the appropriate, pay attention to the volume, too big not); Webpack is also built-in for this support; If you're using Vue
a component (with all its dependencies) instead of an asynchronous load, all you need to do is:
Change to the following wording:
When this is split, other components or other modules that the component relies on are automatically partitioned into the corresponding chunk for asynchronous loading and, of course, the components in the same group are packaged in the same asynchronous chunk by component blocks. This can be very effective in suppressing the Javascript package too large, but also makes the use of resources more rationalized.
Production environment, compression obfuscation and removal of console
The development of medium-scale modernization, differentiation 开发环境
, 测试环境
and 生产环境
, according to the needs of different treatment, has become the industry consensus; if possible, there will be 预发布环境
. In the production environment, the compression confusion can effectively reduce the volume of the package, and if it is possible to remove the use of more frequent console
, rather than simply replacing the empty method, it is also a wonderful small optimization. If you use a UglifyJsPlugin
plug-in to compress the code, add the following configuration to remove the code console
:
1 2 3 4 5 6 7 8
|
Webpack.optimize.UglifyJsPlugin ({ { False, True, [' Console.log '] }, False })
|
Webpack3 new features: Scope hoisting
As of Now (17-08-06), the latest version of Webpack is 3.4.1;webpack in version 3.0, providing a new feature: Scope Hoisting
"Scope Promotion". Simply add a new plug-in to the configuration file, and you'll be able to make the Webpack packaged with smaller, faster-running code files:
1 2 3 4 5
|
Module. Exports = { Plugins: [ New Webpack. Optimize. Moduleconcatenationplugin () ] }
|
It is learned that this Scope Hoisting
and Tree Shaking
, initially, are implemented by Rollup. In the practice of the individual, this function of the injection, although the volume of packaging has an impact, but not very obvious, interested in the pot can try; More on this feature message, see Webpack 3 new features: Scope hoisting.
This article since the beginning of this month (08) fourth to continue to write, the original content intended to involve the Webpack
packaging optimization of the volume and speed of two aspects; considers, near the time of writing (No. 06 night), has not been remembered how long the MAC has not been shut down, unexpectedly has been restarted; the leakage of the house is always automatically synchronized (30min) The Operation tribe, unexpectedly did not give the synchronization, wtf! The whole weekend of hammering, all wasted, tears tear eyes??。 Helpless under, had to re-write, until late at night, only to complete the part about volume optimization; After all, the content is more, simply, divided into two parts to accomplish??。 Also here to remind the broad pen pal, timely backup data and confirm, this is very important??。 In this also the next article "Webpack Packaging optimization Speed", of course, this article is also thrown in the perfect.
[Turn] Webpack Package optimization Volume