Pubudu Dodangoda
Pubudu Dodangoda

Reputation: 2874

How to prevent inheriting packages from parent node_modules

First I will give some context to the problem.

I am developing an npm library. Inside the project folder, I have another folder called "example", for testing the library. The structure looks like below.

|- node_modules/
|- src/ 
|- example/
|   |- node_modules/
|   |- src/
|   |- package.json
|- package.json 

The root package.json has the dependency babel-jest. The example/package.json has the dependency react-scripts. When running react-scripts start inside example directory, it gives the following error,

Error screenshot


As far as I can understand, this is because, the package.json inside the example/ directory inherits (not sure if this is the right term) the dependencies of the root package.json.

That is, I can use a dependency installed in the root package.json, inside the src/ of the example/ This is convenient in some cases. But this is a blocker for my use case.

How can I prevent this behaviour? (without changing the directory structure)

Thank you.

Upvotes: 10

Views: 3081

Answers (2)

Victor Axelsson
Victor Axelsson

Reputation: 1466

Two viable options are to either set a prefix or do some scripting to merge the two node_modules folders.

Merging the two folders

PACKAGES=$(cat package.json | jq -r '.dependencies' | jq 'keys_unsorted' | jq -r '.[]')
for p in $PACKAGES; do
    # Check if the parent have it
    [[ ! -d "../../node_modules/$p" ]] && echo "$p directory exists!"

    # Check if the local path have it
    [...]
done

Installing with prefix

npm install --prefix ./

Another thing to consider is if you are working in a application and use some other package. For some reason, that I don't fully understand I could not get it to work when using a workspace package unless that package was distributed on npm. But for some reason it did find it with using the equivalent of the --prefix flag in yarn.

yarn install --modules-folder node_modules

Upvotes: 0

Matthieu Riegler
Matthieu Riegler

Reputation: 55524

From what I understand, Dan Abramov suggests to use SKIP_PREFLIGHT_CHECK=true to work around this problem as there is no real fix.

Upvotes: 4

Related Questions