一 ECMAScript 6的导入和导出:import 、export
1 基本语法
import { dog , person , hero } from './common.js';
import { hello,Plane } from './common.js';
import { car , rain } from './common.js';
import shrimp from './common.js';
console.log(lottery);
console.log(dog,person,hero);
hello();
let plane = new Plane('波音787梦想飞机');
plane.fly();
console.log(car);
rain();
console.log(shrimp);
/****** 单个导出 ******/
// 导出变量
export var dog = '沙皮狗';
export let person = 'Leonardo Da Vinci';
export const hero = '常山赵子龙';
//导出函数
export function hello(){
console.log('hello');
}
// 导出类
export class Plane{
constructor(name){
this.name = name;
}
fly(){
console.log(this.name+'起飞');
}
}
/****** 批量导出 ******/
let car = 'Ferrari 612';
function rain(){
console.log('正在下雨');
}
export { car,rain };
/****** 默认导出 ******/
export default '雀尾螳螂虾';
//export default function(){};
//export default class{};
2 其它事项
(1) 一个变量、函数、类只能被导出一次。
(2) 一个脚本最多只能有一个默认导出语句。
(3) 所有浏览器都不支持导入、导出语法。需要借助babel、webpack等。
二 Node.js的导入和导出:require、exports、module.exports
1 module.exports的属性,会与exports的属性合并。(若属性名相同,则使用exports的属性)
var box = require('./common.js');
console.log(box);
module.exports.person = 'Leonardo Da Vinci'; exports.horse = '赤兔马';
// 命令窗口输出结果
{ person: 'Leonardo Da Vinci', horse: '赤兔马' }
Example app listening at http://:::3000
2 module.exports若被直接赋值,则会忽略exports的属性
var box = require('./common.js');
console.log(box);
module.exports = 'Leonardo Da Vinci'; exports.horse = '赤兔马';
// 命令窗口输出结果 Leonardo Da Vinci Example app listening at http://:::3000
三 TypeScript的导入和导出:import、export
1 基本语法
// 导入一个模块中的某个导出内容
import {person} from './common.ts';
import {Car} from './common.ts';
// 对导入内容重命名
import {Vehical as Auto} from './common.ts';
// 使用模块的默认导出
import hello from './common.ts';
// 将整个模块导入到一个变量,并通过它来访问模块的导出部分
import * as box from './common.ts';
console.log(person);
var car = new Car('Ferrari 488GTB');
car.run('纽伯格林赛道');
var auto = new Auto('Ferrari 599GTB');
auto.run('圣马力诺赛道');
hello('奥路菲');
console.log(box);
export const person = 'Leonardo Da Vinci';
export class Car{
constructor(name:string){
this.name = name;
}
run(place:string):void{
console.log(this.name+'飞驰在'+place);
};
}
export class Vehical{
constructor(name:string){
this.name = name;
}
run(place:string):void{
console.log(this.name+'飞驰在'+place);
};
}
export default function(name:string){
console.log('hello,'+name);
}
// 浏览器控制台输出
Leonardo Da Vinci
Ferrari 488GTB飞驰在纽伯格林赛道
Ferrari 599GTB飞驰在圣马力诺赛道
hello,奥路菲
Object {person: "Leonardo Da Vinci", Car: function, Vehical: function, default: function}
2 其它事项
(1)任何声明(比如变量,函数,类,类型别名或接口)都能够通过添加export关键字来导出。
(2)一个模块只能够有一个default导出。
(3)不推荐使用具有副作用的导入。(例如,import from './common.ts';)
来源:https://www.cnblogs.com/sea-breeze/p/7277100.html