export,export default,exports - 导入导出方法总结

发布时间 2023-06-30 18:19:56作者: 天官赐福·

1.export.default的使用方法

特点:

  1. export.default向外暴露的成员,可以使用任意变量来接收
  2. 在一个模块中,export default只允许向外暴露一次
  3. 在一个模块中,可以同时使用export default 和export 向外暴露成员
//export default-默认导出
const m = 100;
export default m; 

//导入
import m from './file'; //可以改变变量名,如:import a from './file';
//export defult const m = 100;// 不可以这样写
//导出
let a = 100;
let b = {};
let c = ()=>{}

export default {
  a,b,c
}

//导入
import module from './file';
console.log( module.a, module.b, module.c );

2.export的使用用法

特点:

  1. 注意:在一个模块中,export 可以向外暴露多个
  2. 注意;使用export导出的成员,必须严格按照导出时候的名称,不能自定义,来使用 {} 按需接收
  3. 注意;使用export导出的成员,如果要换个名称,可以使用 as 起别名
'use strict';
//导出变量
export const a = '100';  
 
 //导出方法
export const dogSay = function(){ 
    console.log('wang wang');
}

//导出函数
export function catSay(){
   console.log('miao miao'); 
}

//导入- export导出的是多个,需要解构取值
import { a as b, dogSay, catSay } from './file';
//或 import * as utils from './file'
//导出
const str = "export的内容";
const year = 2019;
function message(sth) {
  return sth;
}
export { str, year, message }

//导入
import {str, year, message} from './file';
//或:import * as utils from './file';

3.export和export.default混合导出

//导出
const author = "不要秃头啊";

export const age = "18";
export default author;

//导入
import author, { age } from "./name";

console.log(author, "author");
console.log(age, "age");

4.module.exports的使用方法

特点:

  1. exports 是 module.exports 的一个引用,即 exports = module.exports
  2. module.exports 和 exports 不要同时使用,指向会有问题
//导出
module.exports = { checkIDCIP };

//导入
const { checkIDCIP } = require('./utils'); //或者 import { checkIDCIP } from './utils';

exports的使用

// person.js --- 导出
var name = 'Tom';
var age = 18;

exports.getName = function() {
    return name;
}

exports.getAge = function() {
    return age;
}

// main.js --- 导入
var person = require('./person'); //或 import person from './person'

console.log(person.getName()); // 'Tom'
console.log(person.getAge());  // 18

5.区别总结

  • 其中 export default、export、import 属于ES6产物,module.exports和require属于node.js产物。

  • require:node 和 es6 都支持的引入 (CommonJS规范)

  • export / import:只有es6 支持的导出引入

  • module.exports / exports:只有 node 支持的导出 (CommonJS规范)

  • import 引入依赖包 不需要相对路径,引入其他变量,函数等需要相对路径

参考地址

https://blog.51cto.com/u_15127691/4330800