将代码拆分成更小更易复用的代码块 

JavaScript从ES2015开始支持模块化,一个文件就是一个模块,以前也可以把一个大的JS文件拆分到多个文件里,但容易出现定义的变量、函数名称冲突,文件多了依赖关系也不好管理,上线时觉得a.js文件没什么用就没发布,直到某个功能出现xxx is not a function或者类似的错误才恍然大悟。

现在好了,在语法层次直接支持了模块,相当于新增了一个模块作用域,在这个模块里定义的变量、函数默认就只能在当前模块文件里使用,如果其它模块要用就必须在所属模块导出export,使用时还必须先导入import。

例如定义math模块也就是新建math.js文件并在里面写入相关代码:

function add(x, y) {
  return x + y;
}
function multiply(x) {
  return x * 2;
}
function subtract(x, y) {
  return x - y;
}
function square(x) {
  return x * x;
}

这个时候模块外部想要使用add函数是用不成得,因为没有export.

加上export外部就可以import使用了

math.js:

export function add(x, y) {
  return x + y;
}

export function multiply(x) {
  return x * 2;
}

export function subtract(x, y) {
  return x - y;
}

export function square(x) {
  return x * x;
}

index.js:

import { add, multiply, subtract, square } from "./math";

console.log(add(2, 3));
console.log(multiply(2));
console.log(subtract(2, 3));
console.log(square(2));

除了export还有export default,区别在于使用export导出的成员,使用时需要使用“{成员名称}”的形式import, 而使用export default导出的成员,可以直接使用”import 任意名称 from“的形式导入使用,比如在math.js中export default add:

export default function add(x, y) {
  return x + y;
}

在index.js中使用add:

import addFun from "./math"

其它使用export的还保持原来的引入方式:

import addFun,{multiply, subtract, square} from "./math"

有时候多个模块可能export的成员名称一样,用的时候就可能名称冲突,这个时候可以在import时使用as关键字更改成员在当前模块作用域名称

import {multiply as multiply_math, subtract as subtract_math, square as square_math} from "./math"

也可以直接使用"*"引入整个模块这样使用的时候就可以带上模块前缀避免名称冲突:

import * as math from "./math";
math.default(2,3);//使用export default导出的add
math.multiply(2);//使用export导出的multiply
math.subtract(2,3);//使用export导出的substract
math.square(2);//使用square导出的square