zoukankan      html  css  js  c++  java
  • Main property in package.json defines package entry point

    I know my project's dependencies are installed under node_modules directory. But when I do require('lodash'), how does Node know which file to load?

    "How does Node know which file to read when loading a module?"

    Module loading works in two phases

    When loading a dependency, module loading in Node.js works in two phases. This is in contrast to loading a core node module with require('fs') or a local module with require('./queue/mem.js'). A dependency is loaded in two phases 1) the right directory is looked up and 2) the entry point within that directory is located.

    Finding directory

    Node looks up all node_modules directories that are on the path from the calling file and the root of the filesystem. It starts from the directory containing the file with require call and works all the way up the directory hierarchy. Node keeps looking until it finds a directory name under node_modules directory matching that of the require call. If no directory provides a hit, Node will try few system directories as a last resort.

    Locating entry point

    After finding the directory Node tries a couple of strategies to determining the entry point of the package. The entry point is the file that is to be loaded and its exportsobject to be returned as the return value of the originating require call. First, Node looks for a package.json file and checks if it contains a main property. It will be used to point a file inside the package directory that will be the entry point. If main property does not exist, then Node tries in order index.jsindex.json and index.node.

    What does entry point look like for popular packages

    What is done inside a package, is then up to the module authors. There are a couple of ways to organize the entry point to a package. Here's how some of the popular npm modules do it.

    ModuleMain property in package.json
    lodash "lodash.js"
    async "lib/async.js"
    request "index.js"
    underscore "underscore.js"
    express  
    commander "index"
    debug "./node.js"
    chalk  
    bluebird "./js/release/bluebird.js"

    Entry points of popular npm packages.

    It can be seen that many packages define the main property and only few leave it to the default lookup convention. The express and chalk packages are the only ones to rely on index lookup. For request and commander packages it would not be necessary to be stating index as the entry point since it is be the default.

  • 相关阅读:
    【2020-02-13】内容变了,但计划本身没变
    【2020-02-12】新的工作计划方式
    【2020-02-10】煮饭那点家常
    【2020-02-10】生活需要不断地相互协调
    nacicat premium 快捷键
    python 爬虫之 正则的一些小例子
    Python爬虫之Cookie和Session
    Python爬虫之关于登录那些事
    爬虫常用库之pyquery 库
    day 39 jq 学习入门2
  • 原文地址:https://www.cnblogs.com/chenkeyu/p/11408095.html
Copyright © 2011-2022 走看看