前端笔记

ES6模块化

2018-05-13  本文已影响27人  好奇男孩

ES6 模块

// ES6模块
import { stat, exists, readFile } from 'fs';

ES6 的模块自动采用严格模式

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};
export function multiply(x, y) {
  return x * y;
};
function v1() { ... }
function v2() { ... }

export {
  v1 as streamV1,
  v2 as streamV2,
  v2 as streamLatestVersion
};
function foo() {
  export default 'bar' // SyntaxError
}
foo()

import 命令

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

function setName(element) {
  element.textContent = firstName + ' ' + lastName;
}
import { lastName as surname } from './profile.js';
import {a} from './xxx.js'

a = {}; // Syntax Error : 'a' is read-only;
foo();
import { foo } from 'my_module';
import { foo } from 'my_module';
import { bar } from 'my_module';

// 等同于
import { foo, bar } from 'my_module';

模块的整体加载

// circle.js

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 default 命令

// export-default.js
export default function () {
  console.log('foo');
}
// import-default.js
import customName from './export-default';
customName(); // 'foo'

模块的继承

// circleplus.js

export { area as circleArea } from 'circle';

浏览器加载 ES6 模块

<script type="module" src="./foo.js"></script>
上一篇 下一篇

猜你喜欢

热点阅读