es6模块学习总结

模块功能主要由两个命令构成:exportimport。

export用于输出对外接口,improt用于输人接口

exprot 可以输出变量,也可以输出函数、类。

输出变量的三种写法

// 写法一
export var m = 1;

// 写法二,运用结构赋值
var m = 1;
export {m};

// 写法三
var n = 1;
export {n as m};

输出函数

//在test.js里面输出

export function add(x) {

  return x + 1;

}

也可以写成

 function add(x) {

  return x + 1;

}

export {add};

获取函数

//在main.js里面获取

import add from './test.js'  //'./test.js'是文件路径

add(1)  //2

输出类

写法1

export class Point {

  constructor(x, y) {

    return this.x;

    return this.y;

  }

}

//写法2,跟1差不多

class Point1 {

  constructor(x, y) {

    return this.x;

    return this.y;

  }

}

export {Point,Poiont1}

获取

import {Point,Point1} from './test.js';

var a = new Point(1,2);

前面的例子使用import需要知道变量名与函数名

使用export default 命令获取则不需要

export default function foo() {

  console.log('foo');

}

或者写成

function foo() {

  console.log('foo');

}

export default foo

//test.js

function foo() {

  console.log('foo');

}

export {foo as default}

//main.js

import {default as xxx} from './test.js'

 
原文地址:https://www.cnblogs.com/zhubei/p/6429968.html