Node 18 JavaScript heap out of memory

ok, so heres a weird scenario that happens:

-We have an service that runs on node 14 and we want to update it to 18 but we get constantly 'JavaScript heap out of memory', when you look online it just says to put more ram using node options, this however doesn’t work.

-There is a workaround that we found is that if we do npm i with node 14 and then npm i again it will rebuild the lock file and everything is ok as it should.

-There is also a workaround that you can do npm i --legacy-peer-deps

So my question is what can i do to avoid this? is it one of the packages that is screwing this up? if so how can i find the package thats causing this issue? and why would it cause it?