Is there an npm cli option get package name from local package.json?
NPM has environment variables that it stores. You can see these by typing npm run env
in the console.
You can use this to get the variable you need by grepping for npm_package_name
but that leaves you with "npm_package_name=your_package_name".
One way to get around it would be to get the substring after the "=" character with the command:
cut -d "=" -f 2 <<< $(npm run env | grep "npm_package_name")
This command leaves you with the package name.
EDIT:
Another way to do this is by adding a script in your package.json
that is simply echo $npm_package_name
then run that script in your shell command.
Your package.json
would look something like this:
{
"name": "your_package_name",
"scripts": {
"getName": "echo $npm_package_name"
}
}
Then type npm run getName -s
If you decide to go with your initial idea of using the node
command, you could make it a bit cleaner by using the -p
argument, which is shorthand for --print
:
node -p "require('./package.json').name"
or with error handling
node -p "try { require('./package.json').name } catch(e) {}"