What are phantomChildren in package.json?

Viewed 1860

When I install a module, a list of phantomChildren appears in the package.json file. What are phantomChildren?

1 Answers

I didn't find official documentation for npm package phantomChildren. But encountered some other explanation: https://rushjs.io/pages/advanced/phantom_deps/. It is about rast, but explains behavior of npm dependencies pretty well.

For example library A might import definitions from libraries B and C, but then B and C can both import from D, which creates a “diamond dependency” between these four packages.

A “phantom dependency” occurs when a project uses a package that is not defined in its package.json file.

Some live example:

my-library/package.json

{
  "name": "my-library",
  "version": "1.0.0",
  "main": "lib/index.js",
  "dependencies": {
    "minimatch": "^3.0.4"
  },
  "devDependencies": {
    "rimraf": "^2.6.2"
  }
}

my-library/lib/index.js

var minimatch = require("minimatch")
var expand = require("brace-expansion");  // ???
var glob = require("glob")  // ???

Wait a sec – two of these libraries are not declared as dependencies in the package.json file. How is this working at all!? It turns out that brace-expansion is a dependency of minimatch, and glob is a dependency of rimraf. During installation, NPM has flattened their folders to be under my-library/node_modules. The NodeJS require() function finds them there because it probes for folders without considering the package.json files at all.

To summarize: if package uses dependencies of it's own dependencies, it can be treated as phantomChildren. Package doesn't have such dependencies directly but uses it from other places.

Related