How to prevent yarn install from running twice in Makefile?

Viewed 2276

I have this in my Makefile:

node_modules: yarn.lock
    yarn install --production=false
    touch node_modules

yarn.lock: package.json
    yarn install --production=false
    touch yarn.lock

Basically, if the node_modules directory is missing (or someone has tampered with it by adding/removing files), or yarn.lock has been updated, then it should run yarn install to rebuild/integrity check the node_modules dir.

However, if yarn.lock is missing, it can be rebuilt from package.json, or if package.json is updated, then it should install and rebuild the lock file.

The problem is when both node_modules and yarn.lock are missing, then the same commands run twice.

How can I prevent this?


I can nearly get it to work by wrapping the directives in a conditional:

ifneq ("$(wildcard yarn.lock)","")
node_modules: yarn.lock
    @yarn install --production=false
    touch node_modules

yarn.lock: package.json
    touch yarn.lock
else # yarn.lock does not exist
node_modules: yarn.lock
    touch node_modules

yarn.lock: package.json
    @yarn install --production=false
endif

Now if you touch package.json and then make node_modules and yarn.lock exists, then it'll subsequently touch yarn.lock which will cause node_modules to rebuild, just like I want.

However, if you touch package.json and then make yarn.lock, technically it should attempt a yarn install but it won't because I removed the command from this directive:

yarn.lock: package.json
    touch yarn.lock

To prevent it from running twice in the former scenario.

2 Answers
Related