Modular
In a web application, with the growing scale of the project, modular appearance is an inevitable result. Since the js file which declared variables will be added to the global window object, this is likely to contaminate other global variables, modular appearance, so js files simultaneously and make the project more conducive to safeguarding.
Mainstream module specification
- CommonJS
- ES6 Module
CommonJS
CommonJS definition module is divided into: the module identification (module), the module definition (exports), reference module (require). NodeJS environment module system used is based CommonJS achieved.
Export module
1、 module.exports
module.exports = 1
module.exports = function(){
console.log('fn')
}
module.exports = {
name:'jack',
age:21
}
2、exports
exports.msg = 'hello'
exports.obj = {
name:'jack',
age:21
}
Module introduced
const aM = require('./a')
console.log(aM)
module.exports operating results
exports operating results
CommonJS
Export module into module.exports
and exports
, module.exports
derived will cover the front of the latter, and exports
can be derived simultaneously a plurality. The relationship between the two can be understood as, in the program initialization, performed exports = module.exports = {};
assignment. In fact, require
the exported content is modules.exports
the content of the memory block to perform, not exports
, exports
just modules.exports
a reference to assist modulex.exports
add content.
Simple to understand
var module = { exports: {} }
var exports = module.exports
ES6 Module
ES6
The language level achieved in the module mechanism, and CommonJS
the difference is ES6
static, can not be used anywhere in the file. You can build dependency tree when such behavior makes the compiler, but the ES6
module did not send in your browser, you must use babel
, webpack
packaging tools
export Exports
export const name = "jack"
export const age = "21"
export.default Export
export default function(){
console.log('test')
}
the introduction of import
// 按需引入
import { name,age } from './util.js/a'
// name:'jack' age:21
// 全部引入并取一个别名
import * as aM from './util.js/a'
//{ name:'jack',age:21 }