Using Browserify to realize browser loading of CommonJS
The module of Nodejs is based on CommonJS specification. Can it be used in browser environment?
Var math = require ('math'); math.add (2,3)
The second line math.add (2, 3) runs after the first line require ('math'), so you have to wait for math.js to load. In other words, if it takes a long time to load, the whole application will stop there and wait. This is not a problem for the server side, because all the modules are stored on the local hard disk and can be loaded synchronously, and the waiting time is the read time of the hard disk. However, for browsers, this is a big problem, because the modules are placed on the server side, and the waiting time depends on the speed of the network, which may take a long time, and the browser is in a "fake dead" state.
A tool like browserify can compile the modules of nodejs into modules available to browsers to solve the problems mentioned above. This article will introduce Browserify in detail
Realize
Browserify is the most commonly used tool for CommonJS format conversion.
Take a look at an example where the b.js module loads the a.js module
/ / a.jsvar a = 100% module.exports.a = a *
If index.html references b.js directly, it will report an error, indicating that require is not defined.
/ / index.html Document
At this point, it is time to use Browserify
[installation]
Install browserify using the following command
Npm install-g browserify
[conversion]
Using the following command, you can convert b.js to the format bb.js that is available to the browser
$browserify b.js > bb.js
Check bb.js,browserify to package the a.js and b.js files as bb.js so that they can be run on the browser side
(function e) {function s (ojue u) {if (! n [o]) {if (! t [o]) {var a=typeof require== "function" & & require;if (! upright yoga) return a (ocore0); if (I) return I (ojingo 0); var f=new Error ("Cannot find module'" + o + "'); throw f.codee =" MODULE_NOT_FOUND ", f} var lumped n [o] = {exports: {} T [o] [0] .call (l.exportsdint function (e) {var nimt [o] [1] [e]; return s (n?n:e)}, var i=typeof require== var i=typeof require== "function" & & require;for (var obsolete)