Modular JavaScript

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

Here Insert Picture Description

exports operating results

Here Insert Picture Description
CommonJSExport module into module.exportsand exports, module.exportsderived will cover the front of the latter, and exportscan 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, requirethe exported content is modules.exportsthe content of the memory block to perform, not exports, exportsjust modules.exportsa reference to assist modulex.exportsadd content.
Simple to understand

var module = { exports: {} }
var exports = module.exports

Here Insert Picture Description

ES6 Module

ES6The language level achieved in the module mechanism, and CommonJSthe difference is ES6static, can not be used anywhere in the file. You can build dependency tree when such behavior makes the compiler, but the ES6module did not send in your browser, you must use babel, webpackpackaging 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 }
Published 17 original articles · won praise 0 · Views 393

Guess you like

Origin blog.csdn.net/k19970320j/article/details/104500010