113

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?

rinogo
  • 8,491
  • 12
  • 61
  • 102
  • 1
    Possible duplicate of http://stackoverflow.com/questions/30286498/change-working-directory-for-npm-scripts – rinogo May 06 '16 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](http://ss64.com/nt/cmd.html) –  May 06 '16 at 19:21

2 Answers2

192

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.

Johnner
  • 3,545
  • 1
  • 23
  • 23
  • 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 '17 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 '17 at 18:55
  • `prefix` isn't an option but rather a config setting. It's documented on the `npm-folders` page (https://docs.npmjs.com/files/folders) – JamesQMurphy May 18 '18 at 01:50
  • 2
    there are multiple package.*.json files to work with : how to specify which one? – WestCoastProjects May 26 '21 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? – Kiran Parajuli Dec 15 '22 at 05:21
1

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
ilghar
  • 25
  • 7