Node.js에서 모듈의 가져 오기 및 내보내기 규칙과 원칙 분석

문제 설명

이 블로그는 다음 문제를 해결합니다.

  • module.exports와 exports의 연결 및 차이점
  • Node에서 모듈의 가져 오기 및 내보내기 규칙
  • 원리 분석, 본질에 대한 깊은 이해

1. Node의 모듈 소개

Node는 JavaScript 용 서버 수준 API를 많이 제공하며 이러한 API의 대부분은 명명 된 코어 모듈에 패키지되어 있습니다.

  • 예를 들어, 파일 작업을위한 fs 코어 모듈, http 서비스로 구축 된 http 모듈, 경로 작업 모듈 및 os 운영 체제 정보 모듈
  • 노드에는 전역 범위가없고 모듈 범위 만 있습니다.

require 메서드에는 두 가지 기능이 있습니다.

  • 파일 모듈을로드하고 그 안에있는 코드를 실행합니다.
  • 로드 된 파일 모듈에서 내 보낸 인터페이스 개체 가져 오기

Node에는 세 가지 유형의 모듈이 있습니다.

  1. 핵심 모듈 : fs 파일 운영 모듈, http 네트워크 운영 모듈 등 Node 자체에서 제공
  2. 제 3 자 모듈 : 제 3 자 에 의해 제공되며, npm로드하기 전에 다운로드 해야하는 시간 사용
  3. 사용자가 작성한 모듈 : 파일에 많은 코드를 작성할 때 작성하고 유지하는 것이 쉽지 않으므로 파일의 코드를 여러 파일로 분할하는 것을 고려할 수 있습니다.

2. 규칙 가져 오기 및 내보내기

2.1 여러 멤버 내보내기

방법 1 :

//导出
module.exports.a = 'hello';
module.exports.add = function () {
    
    
  console.log('add');
}

//导入
let test = require('./a.js')
console.log(test);//{ a: 'hello', add: [Function] }

포인트 투 포인트 종류 위에 많은 글이 쓰이기 때문에 너무 많은 문제가 발생 하여 동일한 참조에 대한 exports기본 exports 和 module.exports포인트 인 Node 객체를 제공합니다.

방법 2 :

//导出
exports.a = "hello";
exports.add = function () {
    
    
  console.log("add");
}

//导入
let test = require('./a.js')
console.log(test);//{ a: 'hello', add: [Function] }

방법 3 (권장) :

//导出
module.exports = {
    
    
  a: 'hello',
  add: function () {
    
    
    console.log('add');
  }
}

//导入
let test = require('./a.js')
console.log(test);//{ a: 'hello', add: [Function: add] }

2.2 단일 멤버 내보내기

방법은 한 가지뿐입니다.module.exports = ***

//导出
module.exports = 'hello';

//导入
let test = require('./a.js')
console.log(test);//hello
//导出
module.exports = 'hello';

//后者会覆盖前者
module.exports = function () {
    
    
  console.log('add');
}

//导入
let test = require('./a.js')
console.log(test);//[Function]

exports = ***단일 멤버를 내보낼 수없는 이유 무엇 입니까? 해보자

//导出
exports = 'hello';

//导入
let test = require('./a.js')
console.log(test);
//{} 结果是是一个空对象

3. 원리 분석

  • Node에는 모든 모듈 안에 객체 모듈이 있습니다.
  • 에서 모듈 객체의 속성이 exports, 수출 또한 객체이다
var module = {
    
    
    exports: {
    
    }
}
  • 뿐만 아니라 모듈의 구성원은 다음 exports과 같습니다.module.exports
var exports = module.exports
console.log(exports === module.exports) // => true
  • 기본적으로 코드 끝에는 문장이 있습니다. return module.exports; 즉, 마지막으로 내 보낸module.exports , 우리는 사용하고 requiremodule.exports습니다. 위의 규칙은 모두 맨 아래 수준에서 구현되었으므로 볼 수 없습니다.

  • 코드 데모

// 把下面这些代码想象成模块内部的底层实现

// 每个模块内部都有一个 module 对象
// module 对象中有一个成员 exports 也是一个对象
var module = {
    
    
  exports: {
    
    }
}

// 模块中同时还有一个成员 exports 等价于 module.exports
var exports = module.exports

console.log(exports === module.exports) // => true

// 这样是可以的,因为 exports === module.exports
// module.exports.a = 123
// exports.b = 456

// 对exports重新赋值会断开和 module.exports 的连接,
// 因此这样并不能导出单个成员,因为模块最后 return 的是 module.exports
// exports = function () {
    
    
// }

// 这才是导出单个成员的正确方式
module.exports = function () {
    
    
  console.log(123)
}

// 最后导出的是 module.exports
return module.exports

그림을 그려서 설명하겠습니다.

(1) 내보내기의 재 할당 없음, 기본값 module.exportsexports메모리의 동일한 개체를 가리 킵니다.
여기에 사진 설명 삽입
(2) 내보내기 재 할당, exports연결 해제 및 module.exports연결
여기에 사진 설명 삽입
(3) 연결 관계 참조를 다시 설정하고exports = module.exports


4. 확장 된 읽기

https://blog.csdn.net/weixin_43974265/category_10692693.html

추천

출처blog.csdn.net/weixin_43974265/article/details/111823622