官术网_书友最值得收藏!

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"
  }
}
主站蜘蛛池模板: 札达县| 万盛区| 阿合奇县| 安徽省| 迭部县| 德州市| 龙南县| 白山市| 兴仁县| 扬中市| 宁城县| 日照市| 辽中县| 西林县| 高陵县| 定襄县| 龙山县| 临城县| 寻乌县| 无极县| 静乐县| 邹城市| 宿迁市| 华安县| 偃师市| 诸城市| 揭阳市| 亚东县| 祥云县| 德江县| 北碚区| 张家港市| 临猗县| 紫阳县| 通州市| 鹤岗市| 建昌县| 大埔区| 昌吉市| 万宁市| 乡宁县|