可选的 NPM 依赖安装

Optional NPM dependency installation

我们有一个共享库,它为我们安装了所有引导代码。大多数人使用原始 Javascript 作为前端,但也有少数人使用 Typescript。

package.json 是否也可以包含仅适用于 Typescript 的依赖项列表(如所有 @types 和其他与 Typescript 相关的模块),只有在您提供某些标志?即 运行 npm install 只会安装 "normal" 软件包,但 npm install --some-flag 也会安装其他软件包。

也许您正在寻找的是 optionalDependencies 和 --no-optional 标志的组合使用。

来自 https://docs.npmjs.com/files/package.json :

optionalDependencies

If a dependency can be used, but you would like npm to proceed if it cannot be found or fails to install, then you may put it in the optionalDependencies object. This is a map of package name to version or url, just like the dependencies object. The difference is that build failures do not cause installation to fail.

It is still your program's responsibility to handle the lack of the dependency. For example, something like this:

try {
  var foo = require('foo')
  var fooVersion = require('foo/package.json').version
} catch (er) {
  foo = null
}
if ( notGoodFooVersion(fooVersion) ) {
  foo = null
}

// .. then later in your program ..

if (foo) {
  foo.doFooThings()
}

Entries in optionalDependencies will override entries of the same name in dependencies, so it's usually best to only put in one place.

https://docs.npmjs.com/cli/install 开始:

The --no-optional argument will prevent optional dependencies from being installed.