2 years ago

#49733

test-img

Patrick Kenny

Clearing node_modules in a preinstall script breaks npm install

I am confused about the behavior of the npm preinstall hook.

In my package.json, I added a preinstall script:

"preinstall": "./scripts/preinstall.sh"

And here's preinstall.sh:

#!/bin/bash

# Exit if any command fails.
set -e

# Set the script directory.
SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )"
# Change to the script directory so that relative paths work.
cd "$SCRIPT_DIR" || exit
# Script needs to be executed from repo root.
cd ../ || exit

# Install CKEditor.
# Node modules should be removed to ensure we are working with fresh code.
cd ckeditor5 || exit; rm -rf node_modules; npm install; npm run build
cd ../

# Delete the old modules because sometimes the version will not be updated correctly.
rm -rf node_modules

# npm install will now be run after preinstall hook is complete.

So I run npm install... and node_modules is deleted, but then the packages are not installed.

What I expected to happen

  1. My preinstall script is called, which deletes node_modules.
  2. npm install occurs, installing the packages in package.lock.

What actually appears to be happening

  1. npm install occurs, installing the packages in package.lock.
  2. My preinstall script is called, which deletes node_modules.

This behavior doesn't make sense based on the name "preinstall". So I assume I am doing something wrong.

I want to delete node_modules before installing, as I have had some weird issues where macOS does not properly install packages unless node_modules is cleared (Windows and linux are working fine).

How can I clear the node_modules directly automatically before npm install?

npm

npm-install

npm-scripts

0 Answers

Your Answer

Accepted video resources