首先,我们先有个清晰的了解,这些关键字是用于什么环境
export/import: 只有ES6支持的导出引入
export default: ES6支持的导出,为模块指定默认输出,这样就不需要知道所要加载模块的变量名
require: 只有node支持的引入
module.exports/exports: 只有node支持的导出
好了,有了这个概念,我们就可以有一个清晰的认识。不多说,下面我们直接上代码
export 与 export default 区别
1、export 导出是放到{}中,也可以直接导出变量
const a = 10
const b = 20
export {a, b}
export const c = 30
2、export default 直接导出变量;
但在同一文件中只能是使用一次,否则会抛出错误提示 Syntax Error: SyntaxError: Parsing error: Only one default export allowed per module.
const a = 10
export default a;
const b = () =>{
return 'this is B!';
}
export default b;
3、export 配合 import 使用
const a = 10;
const b = 20;
export {a, b};
export const c = 30;
import {a, b, c} from './index.js';
console.log(a);
console.log(b);
console.log(c);
4、export default 配合 import 使用
const a = 10
export default a;
import a from './index.js';
console.log(a);
-----------
const b = () =>{
return 'this is B!';
}
export default b;
import b from './index2.js';
console.log(b());
5、还有一种 import , 使用 as 关键字
const a = 10;
const b = 20;
const c = () =>{
return 'log C';
}
export {a, b};
export default C;
------------
import * as all from './index.js';
console.log(all.a);
console.log(all.b);
console.log(all.c);
运行打印结果
const a = 10;
export const b = 20;
const c = () => {
return 'this is C!';
};
export { a };
export default c;
------------------
import c, { a, b } from './test';
import * as all from './test';
a:10
b:20
c:() => { return 'this is C!'; }
all.a:10
all.b:20
all.c:undefined
module.exports 与 exports
NodeJS 中为了方便,Node 为每个模块提供一个 exports 变量,指向 module.exports。这等同在每个模块头部,有一行这样的命令。
var exports = module.exports
于是我们可以直接在 exports 对象上添加方法,表示对外输出的接口,如同在 module.exports 上添加一样。注意,不能直接将 exports 变量指向一个值,因为这样等于切断了 exports 与 module.exports 的联系
const a = 100;
console.log(module.exports);
console.log(exports);
exports.a = 200;
module.exports.b = 'this is b!';
exports = 'null';
const a = require('./index');
console.log(a)
console.log(b)
所以说require导入的,其实都是module.exports导出的对象,exports只是一个简写形式,它的指针初始化时,被指向module.exports,可以通过exports.xxx 为module.exports添加值,但后续exports指针改变,不会影响module.exports导出对象的值。
参考文档
exports 和 module.exports 的区别
其他
官方 import 定义
官方 export 定义