esModule与CommonJS(Node)

esModule

Function block mainly composed of two commands: exportand import. exportCommand module for the provision of external interface , importcommand input function provided by other modules.

export order

export var firstName = 'Michael';
export var year = 1958;
export function multiply(x, y) {
  return x * y;
};
var firstName = 'Michael';
var lastName = 'Jackson';
var year = 1958;
function fn(){}

export {
    firstName as a, 
    lastName, 
    year,
    fn
};

Further, exportthe interface outputted sentence, the corresponding values are dynamic binding relationship, i.e., through the interface, may take the values in real time inside the module.

export var foo = 'bar';
setTimeout(() => foo = 'baz', 500);

import command

Use exportafter command defines the external interface module, the other by JS file you can importload the module (file) command.

import {firstName, lastName as name, year} from './profile';
// 整体加载
import * as obj from './profile';

importCommand has a lifting effect, will be promoted to head the entire module, the first implementation

export default command

export:

// export.js
export default function foo() {
  console.log('foo');
}
export var name = 'a'
export var age = 1

// 或者写成

function foo() {
  console.log('foo');
}

export default foo;

import:

// 只输入默认方法的变量
import obj from './export.js'
// 同时输入默认方法和其他变量
import obj,{name,age} from './export.js'

Because the export defaultcommand is only called output defaultvariables, so that it not be followed by a variable declaration statement.

// 正确
export var a = 1;

// 正确
var a = 1;
export default a;

// 错误
export default var a = 1;
​export { es6 as default } from './someModule';

// 等同于
import { es6 } from './someModule';
export default es6;

 

Inheritance module

//a.js
export var name = 'dd'

//b.js
export var age= '11'
//c.js
export {name as a} from './a,js'
export * from './b,js'

 


esModule is static imports

CommonJS dynamic import

esModule output is a reference value, the module output is cached CommonJS value, dynamically updated does not exist


import()

Using the import command can be used only in the top level, import () to be introduced in other scopes dynamically, and is introduced into a subject promise

import('./file').then(data=>{
        console.log(data);
});
// 动态的使用jsonp加载一个新的文件

 

Published 88 original articles · won praise 16 · views 40000 +

Guess you like

Origin blog.csdn.net/qq_36157085/article/details/100035966