Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Optional NPM dependency installation

We have a shared library where it installed all the bootstraping code for us. Most people use raw Javascript for their front end but a few people also use Typescript.

Is it possible for the package.json to also include a list of dependencies that are for Typescript only (like all the @types and other Typescript related modules) that only get installed if you provide a certain flag? i.e. running npm install would only install the "normal" packages but npm install --some-flag would install the additional packages as well.

like image 587
Kousha Avatar asked Mar 31 '26 06:03

Kousha


1 Answers

Perhaps what you're looking for is a combined usage of optionalDependencies and the --no-optional flag.

From 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.

And from https://docs.npmjs.com/cli/install :

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

like image 112
amateur Avatar answered Apr 02 '26 22:04

amateur