Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

npm: run scripts from package.json from anywhere inside the project folder

Tags:

path

node.js

npm

I'm using the scripts section inside the package.json file to store some commands I have to run regularly.

 "scripts": {
    "test": "./test/phantomjs ./test/js/run_jasmine_test.coffee ./test/index.html",
    "rjs": "r.js -o ./js/app.build.js",
    "less": "lessc -x ./css/app.less > ./css/app.css"
  }

in every command I have got a ./ at the beginning of the path - this is why I can only call npm run-script rjs from the project's root directory. is there a way to reference the project's root directory inside the package.json so that I can run e.g. npm test from anywhere in my project?

like image 908
Philipp Kyeck Avatar asked Dec 13 '12 13:12

Philipp Kyeck


People also ask

How do I run npm in a folder?

You can use the option --prefix <path/to/folder> to run NPM command in a particular folder. It works like a cross-platform cd <path/to/folder>; npm ... combination. "start": "node ."

How do I run a npm script in package json?

To define an NPM script, set its name and write the script under the 'scripts' property of your package. json file: To execute your Script, use the 'npm run <NAME-OF-YOUR-SCRIPT>' command. Some predefined aliases convert to npm run, like npm test or npm start, you can use them interchangeably.


1 Answers

I think it depends on the way you organize your project.

I created a sample project just to demonstrate. This is my sample project directory tree:

.
├── dir1
│   └── dir2
├── package.json
├── src
│   └── index.js
└── test
    └── test.js

NOTE: ./dir1/dir2 are just two empty directories for demonstration.

My package.json file looks like this:

{
  "name": "sample",
  "version": "1.0.0",
  "description": "sample",
  "main": "index.js",
  "scripts": {
    "test": "node test/test.js",
    "start": "node src/index.js"
  },
  "author": "yaniv",
  "license": "ISC"
}

Focus on the scripts section, those are two simple line, without considerations about my location.

If I change directory to /dir1/dir2 and execute npm test and the script I wrote on test property is executed properly without the use of ./ (which defines the current directory...)

Bottom line - I suppose if you re-organize your project and remove ./ will do the job in your case.

like image 76
yaniv israel Avatar answered Sep 22 '22 02:09

yaniv israel