Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OS independent access to variables in package.json

To access a variable in npm scripts you would do something like this in your package.json:

"scripts": {
    "preinstall": "echo ${npm_package_name}"
}

The problem is that works only in Unix, not Windows, where you have to use %npm_package_name%.

Is there a way to do this OS independent? It will be good if npm could do such a variable expansion, before invoking the command.

like image 514
Adrian Ber Avatar asked Mar 28 '16 10:03

Adrian Ber


People also ask

Can I use variable in package json?

To use variable, you need to declare a section named config (or something else, but not a name was already taken by the package. json ).

What is private property in package json?

private. If you set "private": true in your package. json, then npm will refuse to publish it. This is a way to prevent accidental publication of private repositories. Follow this answer to receive notifications.

What information can go into a package json file?

Your package. json holds important information about the project. It contains human-readable metadata about the project (like the project name and description) as well as functional metadata like the package version number and a list of dependencies required by the application.

What is dependencies in package json?

The dependencies property of a module's package. json is where dependencies - the other modules that this module uses - are defined. The dependencies property takes an object that has the name and version at which each dependency should be used.


2 Answers

To make it cross-platform, use cross-var:

"scripts": {
    "preinstall": "cross-var echo ${npm_package_name}"
}
like image 62
Mark Woon Avatar answered Oct 17 '22 04:10

Mark Woon


There's no known way to do this that's OS independent.

A good workaround is to execute the command within a node script:

First, change the preinstall command to execute a node script:

"scripts": {
    "preinstall": "node nameEcho.js"
}

Then you define the command in the nameEcho.js file:

// require the package.json file
var pjson = require('./package.json');

// echo the package's name
console.log(pjson.name);
like image 28
gnerkus Avatar answered Oct 17 '22 04:10

gnerkus