"Front-end Build" Webpack instances and front-end performance optimizations

Source: Internet
Author: User
Tags install node

The plan to put the article also moved up.

This article mainly introduces my experience in the process of playing webpack. This paper introduces the installation of Webpack, the use of plug-ins and the loading strategy. Feel the convenience of building tools for front-end optimization work.

One | FISRT

Once upon a time, we are the way to introduce JS resources, I believe it is seldom met. In recent years, Web front-end development has evolved towards normative development. reflected in the following two points:

    1. MVC Development Framework. A lot of benefits (clear logic, program focus on data and performance separation, readability, to avoid and troubleshoot problems ...) )

    2. Build tools abound. A lot of benefits (improve teamwork, and engineering operations to avoid manual handling of trivial and repetitive tasks)

      • Modular development
      • Optimization theory of front end performance, code compression, merging, cache control, extraction of public code, etc.
      • Others include, for example, you can write the source code with ES 6 or coffeescript, and then build the browser-supported ES5

So, the front-end so fun, if there are no front and back end of the project, it is really old-fashioned.

Mainstream build tools

There are many building tools on the market, including Grunt, Gulp, browserify, and so on, and webpack are all packaging tools. But Webpack also has the following features:

    1. In addition to the Grunt,webpack has a rich plug-in, but also with a set of loading (Loader) system. Enable it to support a variety of specifications, including ES6, CommonJS, AMD, and so on, which grunt, gulp do not have.

    2. From the point of view of code obfuscation, Webpack is even more extreme.

    3. The code is fragmented into a processing unit (not a file), making the file shard more flexible.

P.s. Here is a simple comparison, whichever is better or inferior. In fact, the tools are able to meet the needs, the key is to see how to use, the tool is used behind the optimization of the front-end performance of the degree of understanding.

Daini | Second

Webpack Installation and use

Webpack runs under Nodejs, and it and its plugins are managed using NPM (Nodejs's package management tool).

    1. Install node and NPM. To Nodejs official website installs the package, installs can

    2. Global installation Webpack. In the case of networking, execute the command line $NPM install WEBPACK-G.

This to can use Webpack, to Webpack official website to press get Start (http://webpack.github.io/docs/tutorials/getting-started/) steps, Experience one of the simplest build processes.

However, it is not enough to use webpack well, just to run.

Three | Third

Webpack Plug-in

Spend more time on the use of plugins, and the following are some of the issues that you'll be thinking about in a DemoApp build process (these problems are basically met in each project), and let these plugins come together.

One, the document is too large

The DemoApp initial build results are as follows:

This generates a topic.xxx.js, this file is originally very small, estimated only about 10Kb, but the result of the build incredibly fast 1Mb. Load waterfall streams under 3G Network (750KB/S) such as:

This diagram, which embodies the front-end file loading process, exposes several issues:

    1. The very blue pillars pointed to by the arrows above indicate that most of the time is consumed on the load topic.xxxx.js.

    2. All JS file related pillars are one end of the other before beginning, indicating unreasonable file merge policy, resulting in file serial loading.

    3. As a result, as the arrows at the bottom see, the load time of the page is too long (3G network, + + seconds).

Observation of the built files, found that the original building tools to react, jquery and other code libraries merged into the topic.xxxx.js, resulting in this file is too large. What if we add an activity module? Obviously, activity.xxx.js get similar results, are too big, and react, jquery and other code libraries are repeatedly merged into the activity and topic, such as. if plus the module will get the same result, the more the more repeated loading of the module is more serious situation .

Visible, the extraction of Public code, the situation can be improved, in addition, compression code can undoubtedly make the file smaller.

1. extract react, jquery and other library files. They rarely change, and are reused everywhere, should be extracted, and get long-time caches.

The plugin is used here:webpack.optimize. Commonschunkplugin (Webpack built-in plug-in)

2. Code compression. react compressed from 700+ KB to 100+ kb

Plugin used here:WebPack.optimize.UglifyJsPlugin (WebPack built-in plugin)

After processing topic.xxx.js and activity.xxx.js are very small, and many jquery.xxx.js and react.xxx.js

Then look at the file load waterfall stream, the proportion of the pillars is short, while the resources parallel loading.

At this point, the problem is better solved, but not enough, as the project grows larger, there is an important factor that can lead to large files. This part of the content is presented at the end of this article.

Second, how to cache

Cache control to do two things, mention cache hit ratio

    1. Get files from the cache for files that are not modified

    2. Do not get from the cache for files that have been modified

Around these two points, the deduction of a lot of solutions, here are listed two kinds:

    • Do not process, wait for user browser cache to expire, update automatically. This is the most lazy, low-hit, and there may be some files are not updated, resulting in an error situation.

    • The HTTP header sets a large max-age for the file, for example 1. At the same time, give each file name on the file with the version number, for example, the hash value of the file as the version number, topic. Ef8bed6c.js. That is, to keep the file for a long period of time.

        • When a file is not updated, using the cached file naturally does not go wrong;

        • When the file has been updated, its hash value will inevitably change, when the file name has changed, naturally there is no cache of this file, so the browser will load the latest files.

From the above can be seen, through the webpack is easy to do 2nd-only need to configure the file name [Chunkhash:8], where 8 is the hash length of 8, the default is 16.

P.s. This kind of processing effect is very good, but there is also a bad place, that is, the browser to this cache way cache capacity is too small, only 12Mb, and do not divide the host. So the more extreme approach is to file name key, the content of the file is value, slow existence localstorage, hit from the cache to take, not hit the server to take, although the cache capacity is only 5Mb, but each host is exclusive of this 5Mb.

Iii. Automatic generation of pages

File name with the version number, each time the file changes, the HTML file will need to manually modify the referenced file name, this duplication of work is trivial and error prone.

Use the htmlwebpackplugin and extracttextplugin plug-ins to resolve this issue.

    • Create a page with JS

    • Create a page with CSS

New Extracttextplugin ("Comm.[contenthash:9].css")

Plug-in introduction ends here, however, there is a problem with synchronous loading and asynchronous loading, or the portal file will be bloated.

Restaurant | Fourth

About synchronous loading and asynchronous loading

The best thing to do with Webpack is that you can require files directly as you do server programming, and it appears that you are using the files directly from the server in a synchronized manner. Like the code below, there is no asynchronous logic and the code is clean.

However, this kind of cool is at a price, for the direct require module, the webpack approach is to pack the dependent files together, resulting in a bloated file.

So when writing code to pay attention to moderate synchronous loading, synchronization of the code will be synthesized and packaged together, asynchronous loading code will be fragmented into a chunk, when the module needs to be loaded again, that is, loading on demand , this degree is for developers to grasp, Synchronous loading of too much code can cause too much file load speed, too many asynchronous files are too broken, resulting in excessive HTTP requests, as well as loading speed.

    • The notation for synchronous loading, such as:

var Topicitem = require ('.. /topic/topicitem ');

    • The notation for asynchronous loading, such as:

A principle is: the first screen needs synchronous loading, the first screen after the need to load (async) on Demand

Conclusion

The above is a good practice of building tools Webpack, can be seen, to use good or very test front-end performance optimization of the power, compare when synchronization, when asynchronous, if do cache and so on.

If you find the article useful, click on the recommendation below

"Front-end Build" Webpack instances and front-end performance optimizations

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.