前端工程化js css htmlES6 新特性

ES6 Module语法

2022-05-11  本文已影响0人  生命里那束光

一、概述

1. 模块概念:

  • 模块(module)体系,将一个大程序(大型的复杂项目)拆分成互相依赖的小文件,再用简单的方法拼装起来。

其他语言都有这项功能,比如 Ruby 的require、Python 的import,甚至就连 CSS 都有@import

  • ES6 之前,社区制定了一些模块加载方案,最主要的有 CommonJS 和 AMD 两种。

浏览器端模块化规范:AMD、CMD

服务器端模块化规范:CommonJS

2. ES6模块Module概念

3. ES6(静态加载)对比CommonJS(运行时加载):

  • CommonJS 模块就是对象,输入时必须查找对象属性。
// CommonJS模块
let { stat, exists, readfile } = require('fs');

// 等同于
let _fs = require('fs');
let stat = _fs.stat;
let exists = _fs.exists;
let readfile = _fs.readfile;

上面代码的实质是整体加载fs模块(即加载fs的所有方法),生成一个对象(_fs),然后再从这个对象上面读取 3 个方法。这种加载称为“运行时加载”,因为只有运行时才能得到这个对象,导致完全没办法在编译时做“静态优化”。

  • ES6 模块不是对象,而是通过export命令显式指定输出的代码,再通过import命令输入。
// ES6模块
import { stat, exists, readFile } from 'fs';

上面代码的实质是fs模块加载 3 个方法,其他方法不加载。这种加载称为“编译时加载”或者静态加载,即 ES6 可以在编译时就完成模块加载,效率要比 CommonJS 模块的加载方式高。

4. ES6模块的优势

由于 ES6 模块是编译时加载,使得静态分析成为可能。

二、严格模式

ES6 的模块自动采用严格模式,不管你有没有在模块头部加上"use strict";

严格模式主要有以下限制。

  • 变量必须声明后再使用
  • 函数的参数不能有同名属性,否则报错
  • 不能使用with语句
  • 不能对只读属性赋值,否则报错
  • 不能使用前缀 0 表示八进制数,否则报错
  • 不能删除不可删除的属性,否则报错
  • 不能删除变量delete prop,会报错,只能删除属性delete global[prop]
  • eval不会在它的外层作用域引入变量
  • evalarguments不能被重新赋值
  • arguments不会自动反映函数参数的变化
  • 不能使用arguments.callee
  • 不能使用arguments.caller
  • 禁止this指向全局对象
  • 不能使用fn.callerfn.arguments获取函数调用的堆栈
  • 增加了保留字(比如protectedstaticinterface

其中,尤其需要注意this的限制。ES6 模块之中,顶层的this指向undefined,即不应该在顶层代码使用this

三、export命令(部分暴露)

  • export命令用于规定模块的对外接口,import命令用于输入其他模块提供的功能。。

    1. 一个模块就是一个独立的文件。该文件内部的所有变量,外部无法获取。

    2. 为了让外部能够读取模块内部的某个变量,就必须使用export关键字输出该变量。

1. export输出变量的三种写法
// profile.js
export var firstName = 'Michael';
export var lastName = 'Jackson';
export var year = 1958;
// profile.js
var firstName = 'Michael';
var lastName = 'Jackson';
var year = 1958;

export { firstName, lastName, year };
function v1() { ... }
function v2() { ... }

export {
  v1 as streamV1,
  v2 as streamV2,
  v2 as streamLatestVersion
};
2. export输出函数和类
export function multiply(x, y) {  //输出函数
  return x * y;
};

export class Phone(){         //输出类
    constructor(brand,price) { 
        this.brand = brand; 
        this.price = price; 
    }
}

四、import命令(部分加载)

// main.js
import { firstName, lastName, year } from './profile.js';

function setName(element) {
  element.textContent = firstName + ' ' + lastName;
}
  1. 上面代码的import命令,用于加载profile.js文件,并从中输入变量。
  2. import命令接受一对大括号,里面指定要从其他模块导入的变量名。
  3. 大括号里面的变量名,必须与被导入模块(profile.js)对外接口的名称相同。
4.1 引入方法重命名

如果想为输入的变量重新取一个名字,import命令要使用as关键字,将输入的变量重命名。

import { lastName as surname } from './profile.js';

4.2 import几个注意点
  • import命令输入的变量都是只读的,因为它的本质是输入接口。也就是说,不允许在加载模块的脚本里面,改写接口。
  • import后面的from指定模块文件的位置,可以是相对路径,也可以是绝对路径。如果不带有路径,只是一个模块名,那么必须有配置文件,告诉 JavaScript 引擎该模块的位置。
  • import命令具有提升效果,会提升到整个模块的头部,首先执行。import命令是编译阶段执行的,在代码运行之前。
  • 由于import是静态执行,所以不能使用表达式和变量,这些只有在运行时才能得到结果的语法结构。
  • 多次重复执行同一句import语句,那么只会执行一次,而不会执行多次。
  • import语句会执行所加载的模块,因此可以有下面的写法:import 'lodash';

五、export default 命令 (全部暴露)

var a = "My name is Tom!";
export default a; // 仅有一个
// error,default 已经是对应的导出变量,不能跟着变量声明语句  export default var c = "error"; 
 
import b from "./xxx.js"; // 不需要加{}, 使用任意变量接收

六、 import * from ''(整体加载)

除了指定加载某个输出值,还可以使用整体加载,即用星号(*)指定一个对象,所有输出值都加载在这个对象上面。

//下面是一个circle.js文件,它输出两个方法area和circumference。
export function area(radius) {
  return Math.PI * radius * radius;
}

export function circumference(radius) {
  return 2 * Math.PI * radius;
}

//下面是一个main.js文件
//第一种逐条加载方式
import { area, circumference } from './circle';

console.log('圆面积:' + area(4));
console.log('圆周长:' + circumference(14));

//第二种整体加载方式
import * as circle from './circle';

console.log('圆面积:' + circle.area(4));
console.log('圆周长:' + circle.circumference(14));

注意:引入的模块方法是静态分析的,不允许重写(是从别的模块里拿过来用的)

七、export和import的复合写法(转发)

如果在一个模块之中,先输入后输出同一个模块,import语句可以与export语句写在一起。

export { foo, bar } from 'my_module';

// 可以简单理解为
import { foo, bar } from 'my_module';
export { foo, bar };

上面代码中,exportimport语句可以结合在一起,写成一行。但需要注意的是,写成一行以后,foobar实际上并没有被导入当前模块,只是相当于对外转发了这两个接口,导致当前模块不能直接使用foobar

7.1 输出接口重命名
  1. 模块的接口改名和整体输出,也可以采用这种写法。
// 接口改名
export { foo as myFoo } from 'my_module';

// 整体输出
export * from 'my_module';
  1. 默认接口的写法如下。
export { default } from 'foo';
  1. 具名接口改为默认接口的写法如下。
export { es6 as default } from './someModule';

// 等同于
import { es6 } from './someModule';
export default es6;
  1. 同样地,默认接口也可以改名为具名接口。
export { default as es6 } from './someModule';
  1. ES2020 之前,有一种import语句,没有对应的复合写法。
import * as someIdentifier from "someModule";
  1. ES2020补上了这个写法。
export * as ns from "mod";

// 等同于
import * as ns from "mod";
export {ns};

八、模块的继承

假设有一个circleplus模块,继承了circle模块。

// circle.js
export function area(radius) {
  return Math.PI * radius * radius;
}

export function circumference(radius) {
  return 2 * Math.PI * radius;
}
export default function add(){} //父模块的默认方法,会在全部继承时被忽略

// circleplus.js

export * from 'circle';  //继承circle父模块的所有属性和方法
export var e = 2.71828182846;  //子模块新增的e变量
export default function(x) {   //子模块的默认方法
  return Math.exp(x);
}


export { area as circleArea } from 'circle';
//也可以只继承父模块`circle`的部分属性或方法,改名后再输出。
//上面代码表示,只输出`circle`父模块的`area`方法,且将其改名为`circleArea`。

上面代码中的export *,表示再输出circle模块的所有属性和方法。注意,export *命令会忽略circle模块的default方法。然后,上面代码又输出了自定义的e变量和默认方法。

8.1 继承模块的加载
// main.js

import * as math from 'circleplus'; //加载 子模块circleplus 的所有属性和方法,重命名为math
import exp from 'circleplus';  //将 子模块circleplus 的默认方法加载为exp方法。
console.log(exp(math.e));

上面代码中的import exp表示,将circleplus模块的默认方法加载为exp方法。

九、跨模块常量(全局常量)

const声明的常量只在当前代码块有效。如果想设置跨模块的常量(即跨多个文件),或者说一个值要被多个模块共享,可以采用下面的写法。

// constants.js 模块
export const A = 1;
export const B = 3;
export const C = 4;

// test1.js 模块
import * as constants from './constants';
console.log(constants.A); // 1
console.log(constants.B); // 3

// test2.js 模块
import {A, B} from './constants';
console.log(A); // 1
console.log(B); // 3

如果要使用的常量非常多,可以建一个专门的constants目录,将各种常量写在不同的文件里面,保存在该目录下。

// constants/db.js
export const db = {
  url: 'http://my.couchdbserver.local:5984',
  admin_username: 'admin',
  admin_password: 'admin password'
};

// constants/user.js
export const users = ['root', 'admin', 'staff', 'ceo', 'chief', 'moderator'];

然后,将这些文件输出的常量,合并在index.js里面。

// constants/index.js
export {db} from './db';
export {users} from './users';

使用的时候,直接加载index.js就可以了。

// script.js
import {db, users} from './constants/index';

十、import()动态加载模块

ES2020提案 引入import()函数,支持动态加载模块

import(specifier)

上面代码中,import函数的参数specifier,指定所要加载的模块的位置。import命令能够接受什么参数,import()函数就能接受什么参数,两者区别主要是后者为动态加载。

import()返回一个 Promise 对象。

//例子
const main = document.querySelector('main');

import(`./section-modules/${someVariable}.js`)
  .then(module => {
    module.loadPageInto(main);
  })
  .catch(err => {
    main.textContent = err.message;
  });
适用场合

下面是import()的一些适用场合。

(1)按需加载。

import()可以在需要的时候,再加载某个模块。

button.addEventListener('click', event => {
  import('./dialogBox.js')
  .then(dialogBox => {
    dialogBox.open();
  })
  .catch(error => {
    /* Error handling */
  })
});

上面代码中,import()方法放在click事件的监听函数之中,只有用户点击了按钮,才会加载这个模块。

(2)条件加载

import()可以放在if代码块,根据不同的情况,加载不同的模块。

if (condition) {
  import('moduleA').then(...);
} else {
  import('moduleB').then(...);
}

上面代码中,如果满足条件,就加载模块 A,否则加载模块 B。

(3)动态的模块路径

import()允许模块路径动态生成。

import(f())
.then(...);

上面代码中,根据函数f的返回结果,加载不同的模块。

上一篇下一篇

猜你喜欢

热点阅读