114

I use npm scripts to build my project. I'd like to be able to run the scripts from a different directory. That is, instead of doing the following:

cd project;
npm run build;
cd ..

...I'd like to simply do something like:

npm run build -config project/package.json;

or

npm run build -wd project;

Is this possible?

2
  • 1
    Possible duplicate of stackoverflow.com/questions/30286498/…
    – rinogo
    May 6, 2016 at 18:21
  • I don t think it is possible as i have not found the related switch to tell npm the wd. But, i guess you could call your commands within a sub shell like this cmd /C "cd C:\ && npm -v" see more here
    – user4466350
    May 6, 2016 at 19:21

2 Answers 2

195

Using --prefix worked for me:

npm --prefix /path/to/project run build

Where path/to/project is the directory where your package.json with build command defined.

5
  • this mostly works for me, but I can't fine much documentation on --prefix is minimal. I have a path like /path/to-my-project/, and it doesn't seem to be working. the other npm dependencies are going into different project folders instead of the node_modules folder. Is there a way to escape these arguments? I tried single and double quotes...
    – ps2goat
    Mar 21, 2017 at 23:02
  • 1
    This worked great in my "Pre-build" Visual Studio event. It's wierd that I didn't see --prefix option in NPM documentation.
    – dance2die
    May 21, 2017 at 18:55
  • prefix isn't an option but rather a config setting. It's documented on the npm-folders page (docs.npmjs.com/files/folders) May 18, 2018 at 1:50
  • 2
    there are multiple package.*.json files to work with : how to specify which one? May 26, 2021 at 21:05
  • scripts works but the package-lock.json file is created at the place where I execute the command. Can I avoid that too? Dec 15, 2022 at 5:21
2

to change the path of package.json that npm gets this didnt work for me

npm --prefix /path/to/project run build

but this did

npm --prefix /path/to/project run

but this does not permanently change it for example you can say

npm --prefix /path/to/project run test

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.