esModule
Function block mainly composed of two commands: export
and import
. export
Command module for the provision of external interface , import
command 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, export
the 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 export
after command defines the external interface module, the other by JS file you can import
load the module (file) command.
import {firstName, lastName as name, year} from './profile';
// 整体加载
import * as obj from './profile';
import
Command 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 default
command is only called output default
variables, 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加载一个新的文件