Search code examples
reactjsnpmcreate-react-appsentry

package.json reference value from external json


I have a metadata.json file which includes some values:

{"build":{"major":0,"minor":88}}

In my create-react-app project, I need to run the script to upload sentry map files:

"sentry" : "sentry-cli releases files 0.88 upload-sourcemaps --validate ./build"

where the 0.88 should be pulled from the metadata.json file. I can then run it with:

npm run sentry

How can I pull the value 0.88 from the metadata.json file with build major/ minor and insert it into the sentry command?


Solution

  • I am not sure if there is a solution to do this via package.json.

    Below are the steps I would have taken to solve this problem:

    1. Create a new js file. Let's say the name is run-command.js.
    2. Add a line node ./run-command.js under the script object in package.json.
    3. Import the metadata.json file in this newly created file and extract the necessary data
    4. Execute your command

    Example:

    package.json

    scripts: {
      "sentry": "node ./run-command.js"
    }
    

    run-command.js

    const metadata = require('./metadata.json');
    const { exec } = require('child_process');
    
    exec(`echo ${metadata.build.major}`, (err, stdout, stderr) => {
      if (err) {
        // node couldn't execute the command
        return;
      }
    
      // the *entire* stdout and stderr (buffered)
      console.log(`stdout: ${stdout}`);
      console.log(`stderr: ${stderr}`);
    });
    

    Replace echo with your command. It would look something like ./node_modules/.bin/sentry ...

    You can use a bash script like ./sentry.sh if you are comfortable with shell scripts.