Learning records-related specifications for front-end modularization

1. ES6Modularity (a unified modularization specification)

In ES6before the birth of modular specification, Javascriptthe community has made to try and AMD, CMD, CommonJSand other modular specification.

However, the modular standards proposed by these communities still have certain differences and limitations, and they are not common modular standards for browsers and servers, such as:

  • AMDAnd modularity CMDfor the browser sideJavascript

  • CommonJSJavascriptModularization for server side

Therefore, in the ES6grammar specification, a ES6modular specification is defined at the language level , which is a common modular development specification for the browser side and the server side .

ES6Defined in the modular specification:

  • Each jsfile is an independent module
  • Import module members using importkeywords
  • Expose the use of exportkeywords for module members

2. ES6The basic grammar of modularization

2.1 Default export, default import

  • Default export syntax:export default 默认导出的成员
  • Default import syntax:import 接收名称 from 模块标识符
// 当前文件模块为 m1.js

// 定义私有成员 a 和 c
let a = 10;
let c = 20;
// 外界访问不到变量 d ,因为它没有被暴露出去
let d = 30;

function show() {
    
    };
// 将本模块中的私有成员暴露出去,供其它模块使用
export default {
    
    
    a,
    c,
    show
};
// 导入模块成员
import m1 from './m1.js'

console.log(m1);
// 打印输出的结果为:
// { a: 10, c: 20, show: [Function: show] }

Note : In each module, only one time is allowed export default, otherwise an error will be reported!

2.2 Export on demand, import on demand

  • Export syntax on demand :export let s1 = 10

  • Import syntax on demand :import { s1 } from '模块标识符'

// 当前文件模块为 m1.js

// 向外按需导出变量 s1
export let s1 = 'aaa';
// 向外按需导出变量 s2
export let s2 = 'ccc';
// 向外按需导出方法 say
export function say = function() {
    
    };
// 导入模块成员
import {
    
     s1, s2 as ss2, say } from './m1.js';

console.log(s1); // 打印输出 aaa
console.log(ss2); // 打印输出 ccc
console.log(say); // 打印输出 [Function: say]

Note : In each module, you can use multiple export on demand

2.3 Import and execute module code directly

Sometimes, we just want to simply execute the code in a certain module, and do not need to get the members exposed to the outside of the module. At this time, we can directly import and execute the module code

// 当前文件模块为 m2.js

// 在当前模块中执行一个 for 循环操作
for (let i = 0; i < 3; i++) {
    
    
    console.log(i);
}
// 直接导入并执行模块代码
import './m2.js'

Guess you like

Origin blog.csdn.net/Jack_lzx/article/details/110970672