简体   繁体   中英

How can a bash script in an NPM module access its NPM environment variables?

I need to access npm environment variables of a submodule in a bash script that is running within it, when it is called from a parent NPM module.

Project pseudo-structure:

Parent NPM Project
│
├── node_modules
│   │
│   ├── npm-submodule
│   │   │
│   │   ├── bash-script.sh
│   │   │
│   │   └── package.json
│   .   
│     
├── package.json
│      
.

Parent NPM Project — package.json :

{
  "name": "parent-project",
  "scripts": {
    "get-package-name": "echo $npm_package_name",
    "get-submodule-name": "npm-submodule"
  },
  "dependencies": {
    "npm-submodule": "1.0.0"
  }
}

NPM submodule — package.json :

{
  "name": "npm-submodule",
  "bin": "./bash-script.sh",
  "scripts": {
    "get-package-name": "echo $npm_package_name"
  }
}

NPM submodule — bash-script.sh :

#!/bin/bash

npm run get-package-name

The Problem

From the parent module, when I run npm run get-package-name , predictably parent-project is returned.

When I run npm run get-submodule-name , nothing is returned — it looks like the npm environment variables for the submodule aren't populated within the submodule when it is being called in this way.

In a bash-based context , how can a submodule access it's own NPM environment values, or failing that, read them directly from package.json ?

A solution that I came up with that works is to grab the folder that the bash script is in, and do this:

#!/bin/bash

MODULE_DIR=$(dirname "$(realpath "$0")")
cd "$MODULE_DIR" && npm run get-package-name -s

I tested it with npm link and it works globally within any other NPM project, but am still interested in other solutions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM