>  기사  >  웹 프론트엔드  >  자바스크립트 모듈

자바스크립트 모듈

WBOY
WBOY원래의
2024-09-03 14:11:21998검색
  • 이제 모든 JS를 단일 파일에 작성하여 클라이언트에 보내지 않습니다.
  • 오늘 우리는 모듈 간에 데이터를 공유하고 유지 관리가 더 용이한 코드를 모듈에 작성합니다.
  • 모듈에는 camelCase 이름을 사용하는 것이 관례입니다.
  • jquery, React, webpack, babel 등과 같은 npm 저장소를 통해 자체 코드에 타사 모듈을 포함할 수도 있습니다.
  • 최종 번들은 prod 서버에 배포되어 최종적으로 클라이언트로 전송되는 작은 모듈 파일로 구성됩니다.
  • 이전 브라우저에서는 모듈이 지원되지 않습니다
  • 성능상의 이유로 작은 js 파일을 브라우저로 보내는 것이 좋습니다.
  • 모듈은 JS에서 매우 중요한 부분으로 이미 수십 년 동안 개발자들이 다른 언어에서 사용하고 있습니다.
  • 모듈: 프로젝트의 특정 부분에 대한 구현 세부 정보를 캡슐화하는 재사용 가능한 코드 조각입니다.
  • 독립형 파일이지만 반드시 그럴 필요는 없습니다.
  • 모듈에는 가져오기 및 내보내기도 가능합니다. 기본 ES6 모듈: ES6 이전에는 모듈이 없었습니다. 직접 구현하거나 외부 라이브러리를 사용해야 했습니다. 모듈은 파일당 정확히 하나의 모듈로 저장됩니다.
  • 모듈 등에서 값, 함수 등을 내보낼 수 있습니다. 내보낸 모든 항목을 다른 코드에서 사용할 수 있도록 노출되는 공개 API라고 합니다.
  • 이 공개 API는 공개 코드를 모듈로 가져와서 사용되며 종속성이라고 합니다.
  • 간단한 앱은 모듈 없이도 작성할 수 있지만 기업 규모의 프로젝트에는 모듈이 필요합니다.
  • 고급:
    -> 모듈은 복잡한 애플리케이션을 구축하기 위해 함께 사용하는 작은 구성 요소이므로 소프트웨어를 구성하기가 매우 쉽습니다.
    -> 구성 요소 격리: 각 기능은 다른 개발자의 작업이나 전체 시스템 작동 방식에 대해 걱정하지 않고 완전히 격리되어 개발될 수 있습니다.
    -> 코드 추상화: 모듈에서 낮은 수준의 코드를 구현하고 이러한 추상화를 다른 모듈로 가져오면 자연스럽게 보다 체계적인 코드베이스가 됩니다.
    -> 코드 재사용성: 여러 프로젝트에서도 코드를 재사용할 수 있습니다.

  • 최신 JS는 번들링과 트랜스파일링을 사용합니다.

## Bundling = is a complex process which involves:
a. Eliminate unused Code
b. Combine all modules into single file.
c. Compress the code.
Ex. webpack build tool - requires manual config, hence complex.
Ex. parcel - zero build tool as we don't need to write any setup code.

## Transpiling/Polyfiling:
Convert modern JS to ES5 or older syntax such that older browser supports the application. 
Ex. done using tool called Babel

Entire process results in the final bundle file for production ready to be deployed on server. 
### Scripts are also files but they are different from ES6 modules in the following ways:
Script[used earlier]:
- All top level variables are always global. This leads to global namespace pollution and name-coliision.
- Default mode: Sloppy mode
- Top level 'this' points to window object.
- Import/Export of values is not allowed.
- Linked to html using plain script tag.
- Downloaded by default in sync way, unless async or defer attribute is used.

### ES6 Modules:
- All top-level variables are scoped to module i.e they are private by default. Such a value can be access by outside varible only when its exported by the module else it will be inaccessible for outside world.
- Default mode: Strict mode. Hence with modules no more need to declare strict mode.
- Top level 'this' is 'undefined'
- Allows import/export of values using ES6 syntax of import/export.
- Link to html file using <script type="module"> tag.
- File download always happens in an async way, i.e for module loaded from html or an import one module to another.
## Understanding module import process:
Parsing -> [Asyn module download, Linking import-export, Execute individual module itself] -> Execution overall index.js
- import/export only need to happen at the top level of if-block or any function. Imports are hoisted. Importing values is always the first thing which happens in a module.
- Top-level static imports make imports known before execution. 
- Modules are loaded in async way from the server, importing happens in sync manner. 
- Parsing refers to reading the code without executing it in which imports are hoisted. Modules are imported even before execution. Hence, it enables bundling & code elimation even before fn exection. [V Impt as large projects have 100s of modules, and 3rd party modules also from which we want the small piece and not the entire module]
- Bundlers can then join multiple modules, and then eliminate code. hence, we can easily import/export from code.
- After a module arrives, its parsed and then the module exports are linked to imports in index.js i.e live connection is established between import inside index.js and export statement of the module file. They are not copied. Import is just a reference to the exported value. Hence, when the value changes in the exporting module, it also changes in the importing module too. This concept is unique to ES6 modules, other module system don't work like this.
- Code in the imported modules is executed.

JavaScript Modules

JavaScript Modules

위 내용은 자바스크립트 모듈의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.