1. What is a module/modularity
Before learning js modularization, we need to know what module/modularity is.
Module/modularization : encapsulate a complex program into several blocks (files) according to certain rules (standards), and combine them together. The internal data (implementation) of the block is private, and only exposes some interfaces (methods) to communicate with other external modules.
2. Why use modularity
Websites are becoming web applications, and the complexity of the code increases with the expansion of the website. Developers need highly decoupled JS files/modules to manage the business logic of the web pages. They also need to optimize the code during deployment, so Javascript modular programming, Has become an urgent need.
Third, the benefits of modularity
- Avoid naming conflicts (reduce namespace pollution);
- Better separation, load on demand;
- Higher reusability;
- High maintainability.
Fourth, the modular specification-CommonJS
1. Description
- Each file can be regarded as a module;
- On the server side: the module is loaded synchronously at runtime;
- On the browser side: The module needs to be compiled and packaged in advance.
2. Basic grammar
a. Expose the module
Method 1: module.exports = value
Method 2: exports.xxx = value
b. Import modules
require(xxx)
third-party module: xxx is the module name,
custom module: xxx is the module file path
3. Realize
a. Server-side implementation (Node.js)
(1) Create project structure
(2), define the module code
module1.js
//暴露一个对象 module.exports=value
module.exports={
msg:"module1",
foo(){
console.log("foo()",this.msg);
}
};
module2.js
//暴露一个函数 module.exports=function(){}
module.exports=function () {
console.log("modile2");
};
module3.js
//exports.xxx=value;
exports.bar=function () {
console.log("bar", "module3");
};
app.js
let module1=require("./modules/module1");
let module2=require("./modules/module2");
let module3=require("./modules/module3");
module1.foo();
module2();
module3.bar();
(3) Install node.js and run app.js through node
Command: node app.js
tool: right click -> run
operation result
b. Browser-side implementation (Browserify)
(1) Based on the above, downloadbrowserify
Global:
npm install browserify -g
Local:npm install browserify --save-dev
(2), package processing js
browserify js/src/app.js -o js/dist/bundle.js
(3), create index.html
, introduce in the pagebundle.js
<script type="text/javascript" src="js/dist/bundle.js"></script>
V. Modular Specification—AMD
1. Description
- Dedicated to the browser side
- Module loading is asynchronous
2. Basic grammar
a. Expose the module
(1), define modules without dependencies
define(function(){
return 模块
})
(2), define dependent modules
define(['module1', 'module2'], function(m1, m2){
return 模块
})
b. Import modules
require(['module1', 'module2'], function(m1, m2){
使用m1/m2
})
3. Implementation (browser side)
a. Does not use AMD specifications
(1) Create project structure
(2), define the module code
module1.js
(function (window) {
let msg="module1";
function showMsg(){
console.log(msg);
}
window.showMsg=showMsg;
})(window);
module2.js
(function (window,showMsg) {
data="module2";
function getData() {
console.log(data);
showMsg();
}
window.getData=getData;
})(window,showMsg);
app.js
(function (getData) {
getData();
})(getData);
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>01_NoAMD</title>
</head>
<body>
<script src="js/module1.js"></script>
<script src="js/module2.js"></script>
<script src="js/app.js"></script>
</body>
</html>
(3) Problems caused
There are multiple js added to the page. When loading the page, there are too many requests; module2.js
dependencies module1.js
, so they module1.js
must be placed in module2.js
the front, but in actual development, this dependency relationship is vague and difficult to maintain.
b. AMD specification (Require.js)
(1) Create project structure
(2), define the module code of require.js
module1.js
define(function () {
let msg="require_module1";
function showMsg(){
console.log(msg);
}
return {
showMsg};
});
module2.js
define(function () {
let msg="require_module1";
function showMsg(){
console.log(msg);
}
return {
showMsg};
});
app.js
(function () {
requirejs.config({
baseURL:"js/",
paths:{
module1:"./module/module1",
module2:"./module/module2",
jquery:"./lib/jquery-1.10.1"
}
});
requirejs(['module2','jquery'],function (module2,$) {
$("body").css("background","deeppink");
module2.getData();
});
// requirejs(['module2'],function (module2,) {
// module2.getData();
// });
})();
(3), create index.html
, download require.js
, and .html
introduce in the file
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<script data-main="js/app.js" src="js/lib/require.js"></script>
</body>
</html>
Sixth, modular specification-CMD
1. Description
- Dedicated to the browser side, the loading of the module is asynchronous
- The module will be loaded and executed when it is used
2. Basic grammar
a. Expose the module
(1), define modules without dependencies
define(function(require, exports, module){
exports.xxx = value
module.exports = value
})
(2), define dependent modules
define(function(require, exports, module){
//引入依赖模块(同步)
var module2 = require('./module2')
//引入依赖模块(异步)
require.async('./module3', function (m3) {
})
//暴露模块
exports.xxx = value
})
b. Import modules
define(function (require) {
var m1 = require('./module1')
var m4 = require('./module4')
m1.show()
m4.show()
})
3. Implementation (browser side)
(1) Create project structure
(2), define the module code
module1.js
define(function (require,exports,modules) {
let msg="module1";
function foo() {
console.log(msg);
}
modules.exports={
foo};
});
module2.js
define(function (require,exports,module) {
let data="module2";
function bar() {
console.log(data);
}
exports.bar=bar;
});
module3.js
define(function (require,exports,module) {
let data="module3";
function fun() {
console.log(data);
}
module.exports={
fun}
});
module4.js
define(function (require,exports,module) {
let msg="module4";
let module2=require("./module2");
module2.bar();
require.async("./module3",function (module3) {
module3.fun();
});
function showMsg() {
console.log(msg);
}
exports.showMsg=showMsg;
});
app.js
define(function (require) {
let m1=require("./modules/module1");
let m4=require("./modules/module4");
m1.foo();
m4.showMsg();
});
(3), create index.html
, download sea.js
, and .html
introduce in the file
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>05_CMD_SeaJS</title>
</head>
<body>
<script src="js/libs/sea.js"></script>
<script>
seajs.use("./js/app.js");
</script>
</body>
</html>
Seven, modular specification-ES6
1. Description
- Dependent modules need to be compiled and packaged
2. Basic grammar
a. Expose the module
Expose the module: export
b. Import modules
Import module: import
3. Implementation (browser side)
(1) Create project structure
(2), define the package.json file
{
“name” : “es6-babel-browserify”,
“version” : “1.0.0”
}
(3), install babel-cli, babel-preset-es2015 and browserify
npm install babel-cli browserify -g
npm install babel-preset-es2015 --save-dev
Description : cli: command line interface;
preset preset (package all plug-ins that convert es6 to es5).
(4), define .babelrc file
{
“presets”: [“es2015”]
}
(5), define the module code
module1.js
export function fun(){
console.log("fun() module1");
}
export function fun2() {
console.log("fun2() module2");
}
module2.js
function foo() {
console.log("foo() module2");
}
function bar() {
console.log("bar() module2");
}
export {
foo,
bar
}
module3.js
export default function () {
console.log("默认暴露");
}
app.js
// import $ from "jquery";
import {
fun,fun2} from "./module1";
import {
foo,bar} from "./module2";
import module3 from "./module3";
// $("body").css("background","green");
fun();
fun2();
foo();
bar();
module3();
(5), compile
Use Babel to compile ES6 to ES5 code (but include CommonJS syntax):
babel js/src -d js/lib
Use Browserify to compile js:
browserify js/lib/app.js -o js/lib/bundle.js
(6), create index.html
, .html
introduce the compiled in the filebundle.js
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>06_ES6_ Babel _ Browderify </title>
</head>
<body>
<script src="js/dist/bundel.js"></script>
</body>
</html>
(7), the introduction of third-party modules (jQuery)
Download the jQuery module:
npm install jquery@1 --save
Introduce and use in app.js
import $ from 'jquery'
$('body').css('background', 'red')