1、import 和 export(ES6特性)
目录结构
export_file.js
export const myNumbers = [1, 2, 3, 4];
const animals = ['Panda', 'Bear', 'Eagle']; // Not available directly outside the module
export function myLogger() {
console.log(myNumbers, animals);
}
export class Alligator {
constructor() {
// ...
}
}
let anotherNum = [3, 2, 1];
export { anotherNum, myLogger as Logger }
import_file.js
import * as Utils from './export_file.js';
console.log(Utils)
console.log(Utils.Logger())
console.log(Utils.myLogger())
package.json:这个文件很关键,表示import的是一个module,不然会报错
{
"type": "module"
}
运行结果
也可以把import的方式换成
import {myLogger, Logger, myNumbers as num} from './export_file.js';
console.log(num)
console.log(Logger())
console.log(myLogger())
输出如下
如果把目录结构改成:export单独放,package.json和import文件一起
一样可以正常运行
如果把import单独放
则不能正常运行,会报错MODULE_NOT_FOUND
因此package.json是为了把import_file.js变成一个module,才能使用import
2、exports和require
用require导入一个module,不需要import_file.js自己是一个module,而exports本身将export_file.js以module的形式导出
目录结构
export_file.js
const getName = () => {
return 'Jim';
};
const getLocation = () => {
return 'Munich';
};
const dateOfBirth = '12.01.1982';
exports.getName = getName;
exports.getLocation = getLocation;
exports.dob = dateOfBirth;
import_file.js
const user = require('./export_file');
console.log(user.getName())
console.log(user.getLocation())
console.log(user.dateOfBirth)
console.log(user.dob)
console.log(
`${user.getName()} lives in ${user.getLocation()} and was born on ${user.dob}.`
);
输出
exports的方式改成如下也可以
exports.getName = () => {
return 'Jim';
};
exports.getLocation = () => {
return 'Munich';
};
exports.dob = '12.01.1982';
import中也可以指定导入哪些
const {getName, getLocation, dob} = require('./export_file');
console.log(getName())
console.log(getLocation())
console.log(dob)
console.log(
`${getName()} lives in ${getLocation()} and was born on ${dob}.`
);
3、module.exports和require
module.exports用于只导出一个,比如一个class
目录结构不变
export_file.js
class User {
constructor(name='Jim', age='Munich', dob='12.01.1982') {
this.name = name;
this.age = age;
this.dob = dob;
}
getUserStats() {
return `
Name: ${this.name}
Age: ${this.age}
DateOfBirth: ${this.dob}
`;
}
}
module.exports = User;
import_file.js,将export_file作为整体导入,即得到导出的class
const User = require('./export_file');
let myUser = new User();
console.log(
myUser.getUserStats()
);
运行
也可以用的跟之前exports一样,导出一个dict,里面包含多项内容
module.exports = {
getName: () => {
return 'Jim';
},
getLocation: () => {
return 'Munich';
},
dob: '12.01.1982',
};
import 仍然是
const {getName, getLocation, dob} = require('./export_file');
console.log(
`${getName()} lives in ${getLocation()} and was born on ${dob}.`
);
可以看到跟之前的结果是一样的
exports 和 module.exports 本质上是指向一个地方
比如下面三句是等价的
module.exports = {
dob: '12.01.1982',
};
exports.dob = '12.01.1982';
module.exports.dob = '12.01.1982';
如果输出module来看
最终都会将dob加入到module的exports里面
但需要注意,在我们使用module.exports = {dob: '12.01.1982'};
,是直接将一个object赋值给exports,这将会覆盖exports里的其他内容