- Node.js Blueprints
- Krasimir Tsonev
- 405字
- 2021-07-16 11:36:14
Managing dependencies
Dependency management is one of the biggest problems in complex software. Often, we build our applications around third-party libraries or custom-made modules written for other projects. We do this because we don't want to reinvent the wheel every time.
In the previous sections of this chapter, we used the require
global function. That's how Node.js adds dependencies to the current module. A functionality written in one JavaScript file is included in another file. The good thing is that the logic in the imported file lives in its own scope, and only the publicly exported functions and variables are visible to the host. With this behavior, we are able to separate our logic modules into Node.js packages. There is an instrument that controls such packages. It's called Node Package Manager (npm) and is available as a command-line instrument. Node.js has become so popular mainly because of the existence of its package manager. Every developer can publish their own package and share it with the community. The good versioning helps us to bind our applications to specific versions of the dependencies, which means that we can use a module that depends on other modules. The main rule to make this work is to add a package.json
file to our project. We will add this file with the following code:
{ "name": "my-awesome-module", "version": "0.1.10", "dependencies": { "optimist": "0.6.1", "colors": "0.6.2" } }
The content of the file should be valid JSON and should contain at least the name
and version
fields. The name
property should also be unique, and there should not be any other module with the same name. The dependencies
property contains all the modules and versions that we depend on. To the same file, we can add a lot of other properties. For example, information about the author, a description of the package, the license of the project, or even keywords. Once the module is registered in the registry, we can use it as a dependency. We just need to add it in our package.json
file, and after we run npm install
, we will be able to use it as a dependency. Since Node.js adopts the module pattern, we don't need instruments such as the dependency injection container or service locater.
Let's write a package.json
file for the car example used in the previous sections, as follows:
{ "name": "my-awesome-car", "version": "0.0.1", "dependencies": { "wheels": "2.0.1", "control": "0.1.2", "air": "0.2.4" } }
- TypeScript入門與實戰
- C語言程序設計基礎與實驗指導
- 羅克韋爾ControlLogix系統應用技術
- 人臉識別原理及算法:動態人臉識別系統研究
- C語言實驗指導及習題解析
- Quantum Computing and Blockchain in Business
- MySQL程序員面試筆試寶典
- Visual C++程序設計與項目實踐
- 3D Printing Designs:The Sun Puzzle
- Windows 10 for Enterprise Administrators
- TensorFlow 2.0深度學習應用實踐
- Java從入門到精通(第7版)
- R語言
- Python大數據分析與應用實戰
- Android移動應用程序開發