'How I can skip installing optional dependencies by 'npm ci'?

How I can skip installing optional dependencies from package-lock.json by npm ci?



Solution 1:[1]

You can use npm ci --no-optional . If npm still installs the optional package. Then try after removing package.lock.json and run the command again.

Solution 2:[2]

There was an error in NPM's implementation of npm ci --no-optional. It has been fixed in versions > 6.13.3 - maybe earlier versions as well, but I can only vouch for 6.13.4 and up.

Solution 3:[3]

I was facing this issue with CI workflow script and even "--no-optional" was not working

npm ci --no-optional

The above command only worked when I added the optional package as

"optionalDependencies": {
    "fsevents": "^2.3.2"
}

in the package.json file

Solution 4:[4]

It's not a proper solution, rather an ugly one, but it helped me out. It looks like npm ci --no-optional doesn't work and probably never worked. But at the same time flag --production works. And if we afford mutating package.json (e.g. in a docker container) then...

So I wrote a simple script that:

  • reads package.json content
  • Object.assign(cfg.dependencies, cfg.devDependencies)
  • delete cfg.devDependencies
  • overwrites the initial package.json

So finally we have:

  • dependencies contains both normal & dev dependencies
  • devDependencies section is empty
  • optionalDependencies are intact

And when we run npm ci --production we got what we want - no optional dependencies (in my case cypress). Due to the fact that all these steps are performed inside of a docker container we can mutate package.json.

But I'm not sure that it'll help you too.

Solution 5:[5]

In order to make npm ci --no-optional skip/ignore an optional pacakge, it's important to understand how npm intracts with package.json and pacakge-lock.json.

  1. npm install --no-optional (is only effective if pacakge-lock.json doesn't exists otherwise it would ignore --no-optional)*
  2. npm ci --no-optional is only effective if pakcage-lock.json was already created with npm install --no-optional**.

* This means if you want to make an already installed package an optional, you can would have to

  1. Add it "optionalDependencies": either manulally or through npm install pacakge-name --save-optional
  2. Delete the pacakge-lock.json.
  3. then run rm -rf node_modules/
  4. Lastly run npm install --no-optional
  5. Add this point npm ci --no-optional isn't suppose to install it.

** TIP: you could debug if a certian package is assigned as optional by running npm ls package-name

Note: This one the reason why its recommended to keep trak pacakge-lock.json with git repo of the project.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 oligofren
Solution 3 Syed Zain Jeelani
Solution 4 faiwer
Solution 5