Utilize JSON or an environment file to pass dynamic values to an npm script

I've been working on setting up an npm script for deploying react apps (specifically using create-react-app). However, I'm facing a challenge in setting the S3 bucket url string in either an environment variable or JSON file. This way, I can easily deploy to multiple buckets without having to alter the content of the package.json script each time. Despite my efforts, I haven't been able to figure out how to make this work yet.

Is there anyone who has successfully accomplished this task or has any insight on how it can be done?

Answer №1

One way to access JSON files in your Node.js script is by using the require function. For example, imagine you have a file named "my_config.json" with the following content:

{
    "apiKey": "abc123"
}

Your Node script can then simply include and use this JSON data like so:

var config = require("./my_config.json");

console.log(config.apiKey);

If both files are located in the same directory and you run this script, you will see "abc123" printed to the console. This allows you to easily retrieve settings from external JSON files and utilize them for your application development.

Answer №2

Resolved using an external JavaScript file:

package.json

"scripts": {
    "deploy:staging": "cross-env NODE_ENV=staging node ./scripts/deploy.js",
    "deploy:prod": "cross-env NODE_ENV=production node ./scripts/deploy.js"
},

scripts/deploy.js

const { spawn } = require('child_process')

const env = require('./env.json')

const ls = spawn(
    `yarn build && aws --profile XXXXXX s3 sync build s3://${
        env[process.env.NODE_ENV]
    }`,
    { shell: true },
)

ls.stdout.on('data', (stdout) => console.log(stdout.toString()))
ls.stderr.on('data', (stderr) => console.log(stderr.toString()))
ls.on('close', (code) => console.log(`Closed ${code}`))

env.json

{
    "staging": "STAGING_URL",
    "production": "PRODUCTION_URL"
}

May not be the most elegant solution, but it gets the job done!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issue with padding in Material UI button component not being applied as expected

I am struggling with applying padding and styles to my Material UI component. Take a look at the code snippet below: import "./css/Landing.css"; import { Button } from "@mui/material"; function Landing() { return ( <div class ...

Get rid of any empty space in the image preview icon

Is there a way to eliminate the white space that appears when mixing landscape and portrait images? I want the images to move up and fill the space, even if they don't align perfectly. Additionally, I would like the images to resize based on the scal ...

Utilize AJAX to retrieve the output of a PHP randomizer

Current situation: I have a PHP file with a randomizer function and HTML that utilizes this function to display strings from a separate text document. The Function: <?php function rand_line($fileName, $maxLineLength = 4096) { $handle = @fopen($fileN ...

jQuery's show/hide function exhibiting inconsistencies when checking or unchecking

I have implemented a feature on my webpage where there is a field for previous surgeries with certain elements. The goal is to display the previous surgery elements only if the "previous surgery" checkbox is checked. Below is a snippet of the code I'm ...

Tips for extracting data from a state-based object store in React?

https://i.sstatic.net/A0cc4.pngWhenever I attempt to execute a PUT call, I fetch the data by id and save it in a state named "getData". While I am able to filter and map over this data, I face issues when trying to extract individual values. For instance, ...

Why won't applying a binding style affect the appearance of my Vue component?

const EventLevelBoard = { name: "EventLevel", data: { levelStyle: { display: "block" }, levelStyleinner: [ { display: "block" }, { display: "block" }, { display: "block&qu ...

Hold off on running addThis

My website utilizes Google Maps along with my own JavaScript functions. Additionally, I am integrating the AddThis JavaScript for social sharing buttons. For optimal performance, I need both my custom JavaScript and Google's JavaScript to load and exe ...

Having trouble getting tailwind dark mode to work on next.js?

I have set up a custom boilerplate using next.js(10.0.5) with preact(10.5.12), typescript(4.1.3), and tailwind(2.0.2). I am attempting to incorporate a dark mode feature from Tailwind. I followed the instructions from next-themes in order to add the dark ...

WebApp specifically designed for iPads that mimics the functionality of a swipe

I am in the process of developing a full-screen web application for an iPad that will showcase a series of images in a slider format. The users should be able to swipe between the images and click on one to view it in detail. Below is an example showcasin ...

Scrolling to the latest message in Vuejs when a new message is received

I am currently working on a chat application, but I am facing an issue with scrolling to the bottom when new messages are received. I have attempted both methods: document.getElementById('msg_history').scrollTop = document.getElementById('m ...

Deactivate a button when clicked on a card that has been mapped

After creating a card component and mapping through each card, I added an onClick function to disable the button of the clicked card. However, my logic ended up disabling all buttons instead. Here is the code snippet where I define the rendering of the UI ...

What is the process for inserting a key value pair into a JSON object?

I am looking to enhance my JSON data by including a key-value pair in each object within the array. https://i.sstatic.net/48ptf.png My goal is to insert a key-value pair into every object in the students array. ...

Changing the Style of a CSS Module Using JavaScript

Embarking on a journey into Javascript and React, I am currently working on my first React app. My aim is to adjust the number of "gridTemplateRows" displayed on the screen using a variable that will be updated based on data. Right now, it's hardcode ...

Unable to properly export the HTTP server for socket.io communication

I am facing an issue with my app.js const express = require('express'); const app = express(); const server = require('./server.js'); // app.use const io = require('socket.io').listen(server); io.on('connection', f ...

Include SCSS capabilities to a create-react-app version 1.1.1 project

Is there a straightforward way to add support for .scss files in a create-react-app application without having to create separate .css files and import them? I've checked the documentation, but it only mentions creating .css files. What I really want ...

React - Error: Unable to access the 'props' property because it is undefined

I am working on implementing a click event to delete an item from my list, but I keep encountering the error message "TypeError: Cannot read property 'props' of undefined" whenever I click on it. Although I am striving to follow ES6 standards as ...

Example of jQuery UI tabs - each new tab opens with a unique script assigned

Here is a jQuery tabs script that you can check out: http://jqueryui.com/demos/tabs/#manipulation var $tabs = $( "#tabs").tabs({ tabTemplate: "<li><a href='#{href}'>#{label}</a> <span class='ui-icon ...

The loading animation does not appear in the NextJS 14 - loading.tsx component while a GET request is being processed

Component with 500 photos displayed on my page: 'use client'; import { useEffect, useState } from 'react'; import { wait } from '@/components/loaders/skeletons'; export default function Postings() { const [photos, setPhotos ...

Tips for storing form data in MongoDB

I'm currently working on a form and I need help extracting text from the form in order to save it into MongoDB. Here is an excerpt from my tweets.ejs file: <form method="post" action="/tweets"> <input type="text" id="txt" name="text"/> & ...

One effective way to redirect after a PUT request and display a one-time message

Here's what I'm aiming for in terms of desired behaviour: A user navigates to a password change web page. The user completes the form and it is sent via PUT request to our REST server. Upon successful completion, the user is redirected to their ...