How to hide variables in package.json - reactjs

I have the following scripts in my package.json file
"docker-build": "docker build -t mouchin/my-image-name .",
"docker-push": "docker push mouchin/my-image-name:latest",
"deploy-server": "ssh root#myserverip 'docker pull mouchin/my-image-name:latest'",
"deploy": "npm run docker-build && npm run docker-push && npm run deploy-server"
Problem is that i want to hide
mouchin/my-image-name and root#myserverip
Using some sort of env, maybe saving my variables in .env.prod , but i dont know if i can read the variables saved there directly into package.json

You can use environment variables in your rpm scripts just as you would if you execute the command on the command line (for example $SSH_HOST). However those variables will need to be set directly in the shell that executes the nom script.
Now in order to get the environment variables from an env file loaded, you have to do so manually. For example using a snippet like this:
if [ ! -f .env ]
then
export $(cat .env | xargs)
fi
Source
To execute this before any other script, you could use the built-in lifecylce scripts of npm.
Perhaps, you also want to change the snippet code to load one or the other .env file in case you have one for production and one for development. You will probably be able to use the environment variable NODE_ENV for this, as it is used in most setups, however this last step really depends on your build setup.

Related

Starting React server

I have written my react app and when I run npm start it does bring 'GENERATE_SOURCEMAP' is not recognized as an internal or external command, operable program, or batch file.. I'm using windows 10. Can someone help me with solving this?
My crystal ball says your package.json's "scripts" has something like
"start": "GENERATE_SOURCEMAP=false react-scripts start"
to set the GENERATE_SOURCEMAP environment variable, which would be fine with POSIX shells such as those used by macOS and Linux, but in Windows's command processor.
To run on Windows, you will need to get rid of the GENERATE_SOURCEMAP=false there; if you do want to set the environment variable, do it manually first.
> set GENERATE_SOURCEMAP false
> npm start
The other easy option is to add e.g. cross-env, and do cross-env GENERATE_SOURCEMAP=false react-scripts start.
I solved this by creating file .env.production and putting GENERATE_SOURCEMAP=false there... then you can simply run just react-scripts start

Docker command not able to pass parameter at runtime to a appConfig.json file

Hi i am new to docker(version 19.03.8) and basically I have an angularjs project(dummyPoject) which contains appConfig.json file with the following path dummyPoject\src\assets\conf\appConfig.json. The json file contains the following variable:
{
"baseUrl": "MAPPED-URL"
}
Basically I want to override the MAPPED-URL properties with the one that i am sending while executing docker command.
Based on the online documentation I found out that it can be passed as environment variable while running the docker command please find below:
docker run -e baseUrl=http://localhost:8081/dummyUrl/ -p 8000:8080 -d --name cms test:1.0
I was expecting that MAPPED-URL will change to http://localhost:8081/dummyUrl/ but it is not the case.
Anything I am missing here please?
By adding -e baseUrl=http://localhost:8081/dummyUrl/ to docker run you have successfully added a environment variable to your docker container. But this value will not magically replace values in your appConfig.json file.
You will need some sort of script that extracts the baseUrl variable from environment and replaces the value in the script. This could be done using a bash script which runs when the container starts and replaces the line "baseUrl": "MAPPED-URL" using the environment variable you added.
Update:
This question inspired me to create a small Node.js package command line package that should help solve your issue. The package is called replace-env
You can add replace-env to your package.json dependencies. You can then run the command as part of your Dockerfile build process, or you can have it modify the file at runtime by customizing your CMD instruction.

Get environment variable defined in Linux bash to webpack

I have checked out tons of SO questions about "environment variables in webpack" using e.g. the DefinePlugin:
new webpack.DefinePlugin({'ENV': JSON.stringify('staging')})
but I cannot for the life of me find a way to inject an environment variable defined in the linux bash shell, instead of using the hard coded staging string
In my production and staging environements I have variables such as $ENV and $API_KEY defined, and I want to use their values in my webpack / ReactJs code.
Edit
I notice, if I run the a webpack command from cli:
$ ENVIRONMENT=staging
$ node_modules/.bin/webpack -p
And in my webpack.config.js file defines
new webpack.DefinePlugin({'ENV': JSON.stringify(process.env.ENVIRONMENT)})
This does not work (ENV is undefined in my JS code),
However, if I run it on the same line, it seems to work - ENVIRONMENT seems to be available in the webpack.config.js file:
$ ENVIRONMENT=staging node_modules/.bin/webpack -p
So I would really like to make this work without having to define the ENVIRONMENT variable on the same line as the webpack command.
In nodejs you can get your environment variables via process.env object. In your case you can do process.env.$ENV and process.env.$API_KEY to get $ENV and $API_KEY env vars respectively.
Stupid me forgot to export the variable in the bash terminal
$ export ENVIRONMENT=staging
$ node_modules/.bin/webpack -p
works fine and, as pointed out, one can then access the ENVIRONMENT variable with process.env.ENVIRONMENT from inside webpack.config.js

angular-jsdoc with npm

Using angular-jsdoc I am using this command to generate my docs
node .\node_modules\jsdoc\jsdoc.js app -c .\node_modules\angular-jsdoc\common\conf.json -d docs -t .\node_modules\angular-jsdoc\angular-template\
I don't prefer typing such long command every-time I update my doc.
I would like to know some shortcut so that I can avoid typing or copy/pasting this command.
As the command indicates node is being used for execution. I would suggest using npm 's functionality to create project based commands.
This can be done as follows:
Create a package.json file in your master directory (using npm init).
Add the below json object in package.json file
"scripts": {
"gendoc":"node .\node_modules\jsdoc\jsdoc.js app -c .\node_modules\angular-jsdoc\common\conf.json -d docs -t .\node_modules\angular-jsdoc\angular-template\"
}
This will create a gendoc command for your project which can be executed from the command line as follows:
npm run gendoc
Now you don't need to type entire command, just enter the above command, npm will search for the scripts object in package.json and execute the script whose key is gendoc.

Use custom build output folder when using create-react-app

Facebook provides a create-react-app command to build react apps. When we run npm run build, we see output in /build folder.
npm run build
Builds the app for production to the build folder. It correctly
bundles React in production mode and optimizes the build for the best
performance.
The build is minified and the filenames include the hashes. Your app
is ready to be deployed!
How can we use custom folder instead of /build for the output? Thanks.
With react-scripts >= 4.0.2, this is officially supported:
By default, Create React App will output compiled assets to a /build directory adjacent to /src. You may use this variable to specify a new path for Create React App to output assets. BUILD_PATH should be specified as a path relative to the root of your project.
// package.json
"scripts": {
"build": "BUILD_PATH='./dist' react-scripts build",
// ...
},
or adding a .env file to the root of your project:
# .env
BUILD_PATH='./dist'
Caution: the path specified in BUILD_PATH will be wiped out without mercy. Double check that your environment variable is specified correctly, especially when using continuous integration.
Edit your package.json:
"build": "react-scripts build && mv build webapp"
Create-react-app Version 2+ answer
For recent (> v2) versions of create-react-app (and possible older as well), add the following line to your package.json, then rebuild.
"homepage": "./"
You should now see the build/index.html will have relative links ./static/... instead of links to the server root: /static/....
Edit: Support for a configurable BUILD_PATH just landed into v4.0.2. See t_dom93's answer.
You can't change the build output folder name with the current configuration options.
Moreover, you shouldn't. This is a part of the philosophy behind create-react-app: they say Convention over Configuration.
If you really need to rename your folder, I see two options:
Right after the build process finishes, write a command that copies the build folder content to another folder you want. For example you can try the copyfiles npm package, or anything similar.
You could try to eject create-react-app and tweak the configuration.
If you aren’t satisfied with the build tool and configuration choices, you can eject at any time. This command will remove the single build dependency from your project.
Instead, it will copy all the configuration files and the transitive dependencies (Webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except eject will still work, but they will point to the copied scripts so you can tweak them. At this point you’re on your own.
However, it is important to note that this is a one-way operation. Once you eject, you can’t go back! You loose all future updates.
Therefore, I'd recommend you to not use a custom folder naming, if possible. Try to stick with the default naming. If not an option, try #1. If it still doesn't work for your specific use-case and you're really out of options - explore #2. Good luck!
Support for BUILD_PATH just landed into v4.0.2.
Add BUILD_PATH variable to .env file and run build script command:
// .env file
BUILD_PATH=foo
That should place all build files into foo folder.
Félix's answer is correct and upvoted, backed-up by Dan Abramov himself.
But for those who would like to change the structure of the output itself (within the build folder), one can run post-build commands with the help of postbuild, which automatically runs after the build script defined in the package.json file.
The example below changes it from static/ to user/static/, moving files and updating file references on relevant files (full gist here):
package.json
{
"name": "your-project",
"version": "0.0.1",
[...]
"scripts": {
"build": "react-scripts build",
"postbuild": "./postbuild.sh",
[...]
},
}
postbuild.sh
#!/bin/bash
# The purpose of this script is to do things with files generated by
# 'create-react-app' after 'build' is run.
# 1. Move files to a new directory called 'user'
# The resulting structure is 'build/user/static/<etc>'
# 2. Update reference on generated files from
# static/<etc>
# to
# user/static/<etc>
#
# More details on: https://github.com/facebook/create-react-app/issues/3824
# Browse into './build/' directory
cd build
# Create './user/' directory
echo '1/4 Create "user" directory'
mkdir user
# Find all files, excluding (through 'grep'):
# - '.',
# - the newly created directory './user/'
# - all content for the directory'./static/'
# Move all matches to the directory './user/'
echo '2/4 Move relevant files'
find . | grep -Ev '^.$|^.\/user$|^.\/static\/.+' | xargs -I{} mv -v {} user
# Browse into './user/' directory
cd user
# Find all files within the folder (not subfolders)
# Replace string 'static/' with 'user/static/' on all files that match the 'find'
# ('sed' requires one to create backup files on OSX, so we do that)
echo '3/4 Replace file references'
find . -type f -maxdepth 1 | LC_ALL=C xargs -I{} sed -i.backup -e 's,static/,user/static/,g' {}
# Delete '*.backup' files created in the last process
echo '4/4 Clean up'
find . -name '*.backup' -type f -delete
# Done
I had the scenario like want to rename the folder and change the build output location, and used below code in the package.json with the latest version
"build": "react-scripts build && mv build ../my_bundles"
Here is my solution:
create .env in root, then add this line to it.
BUILD_PATH=$npm_package_name-$npm_package_version
the build path will be "name_of_app"-"version"
these values could be set in package.json
{
"name": "my-app",
"version": "0.1.2",
...
}
Based on the answers by Ben Carp and Wallace Sidhrée:
This is what I use to copy my entire build folder to my wamp public folder.
package.json
{
"name": "[your project name]",
"homepage": "http://localhost/[your project name]/",
"version": "0.0.1",
[...]
"scripts": {
"build": "react-scripts build",
"postbuild": "#powershell -NoProfile -ExecutionPolicy Unrestricted -Command ./post_build.ps1",
[...]
},
}
post_build.ps1
Copy-Item "./build/*" -Destination "C:/wamp64/www/[your project name]" -Recurse -force
The homepage line is only needed if you are deploying to a subfolder on your server (See This answer from another question).
Move command for windows did not work for me. Because it does not copy the "static" folder and subfolders. So I was able to solve this problem using 'ROBOCOPY'.
"build": "react-scripts build && ROBOCOPY build ../my-relative-path/react-app /E",
Quick compatibility build script (also works on Windows):
"build": "react-scripts build && rm -rf docs && mv build docs"
For anyone still looking for an answer that works on both Linux and Windows:
Add this to the scripts section in package.json
"build": "react-scripts build && mv build ../docs || move build ../docs",
with ../docs is the relative folder you want to move the build folder to
Using cross-env is the solution.
Install cross-env:
npm install cross-env
You should update to:
"scripts": {
"build": "cross-env BUILD_PATH='../yourCustomBuildFolder' react-scripts build",
}
Windows Powershell Script
//package.json
"scripts": {
"postbuildNamingScript": "#powershell -NoProfile -ExecutionPolicy Unrestricted -Command ./powerShellPostBuildScript.ps1",
// powerShellPostBuildScript.ps1
move build/static/js build/new-folder-name
(Get-Content build/index.html).replace('static/js', 'new-folder-name') | Set-Content
build/index.html
"Finished Running BuildScript"
Running npm run postbuildNamingScript in powershell will move the JS files to build/new-folder-name and point to the new location from index.html.
Open Command Prompt inside your Application's source.
Run the Command
npm run eject
Open your scripts/build.js file and add this at the beginning of the file after 'use strict' line
'use strict';
....
process.env.PUBLIC_URL = './'
// Provide the current path
.....
Open your config/paths.js and modify the buildApp property in the exports object to your destination folder. (Here, I provide 'react-app-scss' as the destination folder)
module.exports = {
.....
appBuild: resolveApp('build/react-app-scss'),
.....
}
Run
npm run build
Note: Running Platform dependent scripts are not advisable
You have two possibilities:
Change in your package.json the script item into "build": "react-scripts build && mv build webapp" where webapp is your destination folder;
Create .env file in your root directory and insert in it the new definition of build destination folder (ex. BUILD_PATH='./data')
You can update the configuration with a little hack, under your root directory:
npm run eject
config/webpack.config.prod.js - line 61 - change path to: __dirname + './../--your directory of choice--'
config/paths.js - line 68 - update to resolveApp('./--your directory of choice--')
replace --your directory of choice-- with the folder directory you want it to build on
note the path I provided can be a bit dirty, but this is all you need to do to modify the configuration.
webpack =>
renamed as build to dist
output: {
filename: '[name].bundle.js',
path: path.resolve(__dirname, 'dist'),
},

Resources