dietary-wheevil
dietary-wheevil

Reputation: 4481

How To Refer To The `main` Field Value Inside of package.json?

Inside of one's package.json, it's customary to specify the primary (or main) entry point of your module by including a file path (relative to the project's root) as the value for the main field.

Likewise, there is the scripts field, a dictionary whose keys are keywords allowing one to run the associated command passed as its value inside of the terminal. One such commonly seen script allows you to run Node or Nodemon. For illustration, here's an example package.json config:

{
  "name": "example",
  "version": "1.0.0",
  "description": "Example package.json for StackOverflow question",
  "main": "index.js",
  "scripts": {
    "dev": "nodemon index.js"
  },
  "author": "IsenrichO",
  "license": "ISC",
  "dependencies": {
    "express": "^4.13.4",
    "nodemon": "^1.9.1"
  }
}

You'll notice the dev script command in the above runs Nodemon on the index.js file. This file is also the application's entry point as specified in the main field.

My question, then: Is it possible to refer to the file specified by the package.json's main key inside of one of your scripts? In other words, could one write something like

  "scripts": {
    "dev": "nodemon main"
  }

It seems pedantic, but is a genuine question. Appreciate all help!

Upvotes: 4

Views: 1882

Answers (1)

davidhund
davidhund

Reputation: 351

I believe nodemon takes your main script by default so you can just use "dev": "nodemon".

However: you can refer to your package.json's keys with variables using $npm_package_KEY.

In your case:

"scripts": {
  "dev": "nodemon $npm_package_main"
}

Child properties like: $npm_package_author_name

On windows you need to remove the $ and wrap the variable in %:

"scripts": {
  "dev": "nodemon %npm_package_main%"
}

Upvotes: 7

Related Questions