JavaScript: Getting Started with JavaScript modules, and then "module bundle" __java

Source: Internet
Author: User
Tags readable

http://alpha.wallhaven.cc/wallpaper/33246

In the first part of this article, I talked about what modules are, why developers use them, and how to implement modules in your program in different ways.

In this second part, you will answer what the bundle means: why bundle, bundle different methods, and the future development of modules in web development. 1. What is a module bundle

Abstract generalization, modular bundling is such a simple process: To put a set of modules and their dependencies, in the correct order, splicing in a file or a group of files.

But as with all the other aspects of web development, the tricky stuff is always lurking in specifics. 2. Why must I bundle the module?

When you divide a program into modules, they are generally organized into different files or folders. It is likely that you also have a group of library modules, such as underscore, react.

As a result, each of these files has to use the <script> tag to introduce your primary HTML file, which is loaded by the browser when the user accesses your home page. Each file is introduced with a separate <script> tag, meaning the browser has to load them individually.

This is a nightmare for web load time.

So, to solve this problem, we bundle all the files, or "splice" them into a file (sometimes a set of files), just to reduce the number of requests. This is what they talk about when you hear developers talking about "building steps" or "Building processes."

Another common way to accelerate build operations is to "shrink" the bundled code. Reduction is the removal of unwanted characters (such as spaces, comments, line breaks, and so on) in the source code, thereby reducing the overall product of the code without altering its functionality.

Fewer data, and less time for the browser to process, reducing the time it takes to download files. If you've seen a file with a "min" extension, such as "underscore-min.js," you may have noticed that the reduced version is much smaller (but hard to read) than the full version.

Task execution tools, such as Gulp and grunt, make it easier and easier for developers to manipulate stitching and scaling. One side is the human readable code that is shown to the developer, the other side is the bundled computer-readable code provided to the browser. 3. What are the different ways to bundle modules?

If you're using a standard module pattern (discussed in the first section) to define a module, then stitching and shrinking files won't go wrong, and you're actually bundling a bunch of pure JavaScript code into a bunch.

But if you're using a non-native module system, browsers can't parse like Commonjs, AMD, or even the native ES6 module format, you'll need to use specialized tools to translate the code into the correct, browser-aware form. This is when browserify, Requirejs, Webpack, and other modular bundle tools, or module loading tools, are on the up.

In addition to bundling or loading your module, the module bundle has many additional features, such as when you modify or debug the source mapping, it automatically compiles your code.

Here we go. Common Modular Bundle methods: 4. Bundle COMMONJS

As already known from the first part, COMMONJS is a synchronous loading module, although nothing wrong, but not very realistic for browsers. I've mentioned that there are ways to solve this-one of which is the modular bundle tool browserify, which is the tool for compiling COMMONJS modules for browsers.

For example, if you have a file, it introduces a module to calculate the average of a set of values:

var mydependency = require (' mydependency ');
var mygrades = [0];
var myaveragegrade = mydependency.average (mygrades);

In this scenario, we have only one dependency. With this command, browserify bundles all dependent modules recursively into a file for the Portal:

Browserify main.js-  o bundle.js

What Browserify actually does is to jump into a file for each dependency analysis of its abstract syntax tree, thereby traversing the entire dependency of the project. Once it understands your dependency structure, bundle them into a file in the correct order. At that time, you just use a <script> tag, introduce bundle.js to your HTML, so as long as an HTTP request, you download all your source code down. Wow, it's not tied up yet.

Similarly, if you have multiple files and you have multiple dependencies on each file, you have to do it simply: Tell him your entry file, and then you can sit back in your chair and watch the show.

The last generated bundle of files can be directly directed to some tools for compression processing. 5. Bundled AMD

If you are using AMD, you need an AMD module loading tool like Requirejs and Curl. The Module load tool (unlike the module bundle tool) dynamically loads the modules required by your program.

Again, the biggest difference between AMD and COMMONJS is that AMD will load modules asynchronously. So, if you use AMD, you don't need to bundle the modules into a file, and technically you don't have to do the construction of the bundle module action. Because the asynchronous loading module means downloading the files necessary for the program during the run, instead of downloading all the files when the user just enters the page.

Then, in practice, each user action produces an additional request for a large amount of data, which is unreasonable for the product. So most Web developers still use build tools to bundle and shrink their AMD modules for better performance, such as tools like the Requirejs optimizer r.js.

In a nutshell, the difference between AMD and COMMONJS in bundling is that when developed, AMD programs can omit the build process. Until the actual runtime, let r.js those optimization tools involved in processing.

To watch the Commonjs and AMD more interesting "mutual tear", look at this article Tom Dale's blog. 6. Webpack

Bundled tools are a few years old, Webpack is a newcomer. It is designed to allow developers to choose Commonjs, AMD, or ES6, depending on the requirements of the module system you are using.

Do you wonder if there are already a bundle of tools like Browserify and Requirejs, performing well, and why need webpack. Well, at least for one thing, Webpack provides additional useful features, such as "code segmentation"-Dividing your code base into "chunks" loaded on demand.

For example, if you have a Web application where quite a piece of code is used only under certain conditions, it is not efficient to bundle the entire code base into a large file. At this point, you can use the Code partition function, the part of the code to pull away, bundled to another piece, in the execution of the load on demand, so as to avoid in the beginning to encounter a lot of load trouble. In fact, most users will only use the core code of your application.

Code segmentation is just one of the many bright-eyed features provided by Webpack. About Webpack and browserify which is better, the network is full of various viewpoints, the following is some objective and calm discussion, help me to clarify the clue a little: https://gist.github.com/substack/ 68f8d502be42d5cd4942 Http://mattdesl.svbtle.com/browserify-vs-webpack http://blog.namangoel.com/ Browserify-vs-webpack-js-drama 7. ES6 Module

Did you finish it. OK, next I want to talk about the ES6 module, which will reduce the use of bundled tools in the future. (You will soon understand what I mean.) First to understand how the ES6 module was loaded.

The key difference between the ES6 module and the existing JS module format is that it takes the static analysis into account at the beginning of the design. What does that mean. When you import a module, the imported module is parsed in the compile phase, before the code begins to run. As a result, we were able to remove parts of the export module that were not used by other modules before running the program. This saves a lot of space and reduces the pressure on the browser.

So here's the problem. You're using some tools, like uglify.js, to shrink code, and there's a dead code removal process, and it's different from ES6 removing useless modules. Can only say "depends on the situation."

(Note: Dead code removal is an optional step that eliminates unused code and variables.) Just think of it, throw away the redundant parts of the code that don't need to be run after the bundle, it must be after the bundle. )

Sometimes, dead code removal behaves exactly the same in Uglify.js and ES6 modules, and sometimes it is different. If you want to verify, there's a good example in Rollup's wiki.

The difference between ES6 is that it removes dead code differently, called "Tree Shaking", which in essence is the reverse process of dead code removal. It only keeps the code you need to run, rather than excluding what you don't need to run. Take a look at an example:

We have a util.js file with some functions in it, and then export them one by one (exports) using the ES6 syntax:

Export function each (collection, iterator) {if (Array.isarray (collection)) {for (var i = 0; i < Collection.leng Th
    i++) {iterator (collection[i], I, collection);
    } else {for (var key in collection) {iterator (Collection[key], key, collection);
  }} Export function filter (collection, test) {var filtered = [];
    Each (collection, function (item) {if (Test (item)) {Filtered.push (item);
  }
  });
return filtered;
  Export function Map (collection, iterator) {var mapped = [];
  Each (collection, function (value, key, collection) {Mapped.push (iterator (value));
  });
return mapped;
  Export function "Reduce" (collection, iterator, accumulator) {var startingvaluemissing = accumulator = n undefined;
      Each (collection, function (item) {if (startingvaluemissing) {accumulator = Item;
    Startingvaluemissing = false;
    else {accumulator = iterator (accumulator, item);
  }
  });
return accumulator; }

Then, assuming we don't know which functional function our program is going to use, import all of these modules into the main.js:

Import  *  as  Utils from  './utils.js ';

But in the end we've only used each function:

Import * as Utils from './utils.js ';

Utils.each ([1, 2, 3], function (x) {Console.log (x)});

After "tree shaking", the corresponding module loaded in, the new main.js will be like this:

function each (collection, iterator) {
  if (Array.isarray (collection)) {for
    (var i = 0; i < collection.length; I + +) {
      iterator (collection[i], I, collection);
    }
  else {for
    (Var key in collection) {
      iterator (Collection[key], key, collection);}}
;

Each ([1, 2, 3], function (x) {Console.log (x)});

Notice that the only one we use in the export module is brought in.

In addition, if we suddenly decide to use the filter function instead of each, the result would be this:

Import * as Utils from './utils.js ';

Utils.filter ([1, 2, 3], function (x) {return x = = 2});
Related Article

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.