模块import及export

严格模式

  • 字符串'use strict'起始作为标识
  • 由于各浏览器环境对ecmascript某些不明确的地方的实现方式不太一样;为了严格统一而产生的模式
  • ES6的模块自动采用严格模式

主要有如下限制

  • 变量必须声明后在使用
  • 函数的参数不能有同名属性
  • 不能使用with语句
  • 不能对只读属性赋值
  • 不能使用前缀0表示8进制数
  • 不能删除不可删除的属性
  • 不能删除变量delete prop,只能删除 delete global[prop]
  • eval不会在他的外层作用域引入变量
  • eval和arguments不能重新赋值
  • arguments不会自动反应函数参数的变化
  • 不能使用arguments.callee
  • 不能使用arguments.caller
  • 禁止this指向全局对象
  • 不能使用fn.caller和fn.arguments获取函数调用的堆栈
  • 增加了保留字 protected, static , interface

模块

  • 模块体系出现之前的加载方案有 CommonJS[服务器]和AMD[浏览器]两种
  • CommonJS 主要用于node.js 后续针对node.js补充说明
  • 由于浏览器受限于网络请求加载依赖模块数据,AMD["Asynchronous Module Definition"] 实现方式即是异步模块加载
  • 有两个Javascript库实现了AMD规范:require.js和curl.js

ES6模块化

  • 命令构成 export 和 import

export 规定模块对外提供的接口

	profile.js
	export var name = 'zhangsan';
	export var age = 123;
	
	
	profile.js
	var name = 'zhangsan', age = 123;
	
	exprot {
		name, 
		age as newage // as可以用来重命名
	}
	
	profile.js
	export function multiply(x, y ) {
		return x* y;
	}
	
	

import 通过import命令可以加载这个模块(文件)

import { 
	name, 
	age as newage // import同样可以对引入的变量重命名
} from './profile'

特殊写法
export {es6 as default } from './someModule'; //不建议

	==
	
import {es6 } from './someModule';
export default es6;

加载所有
import * as some from './some'

export default

  • 为模块指定默认输出
	export default function() {
		console.log('foo');
	}
	
	import customname from  './test'

ES6模块加载的实质

  • CommonJS模块输出的是一个值的拷贝,而ES6模块输出的是值的引用
  • import是一个动态的引用
  • 避免循环加载

示例

test.js

export default {
	name: '测试default',
	age: 123,
	show: _show
}

function _show() {
	console.info("name: "+ this.name + "; age: " + this.age);
}

test2.js

import test from './test.js'

console.info(test.name);
test.show();

html

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<script src="./js/test2.js" type="module" charset="utf-8"></script>
	</head>
	<body>
	</body>
</html>

console

//测试default
//test.js:8 name: 测试default; age: 123
原文地址:https://www.cnblogs.com/pengsn/p/12963437.html