configuring package.json on windows - reactjs

I'm trying to manage the configuration of a react project on windows, it was previously running on mac. I'm using yarn build. inside the package.json scripts>build was configured as "rm-rf deployment/static;react-scripts build && mv build deployment/static". since the rm-rf and mv commands are for Linux, I tried using rmdir/del and move instead.. but it doesn't seem to work. I'm getting the error: Parameter format not correct - "static".

Windows Solution (cmd.exe)
The equivalent of that build script running via Command Prompt or PowerShell on Windows is:
"scripts": {
"build": "rd /s/q \"deployment/static\" 2> nul & react-scripts build && md \"deployment/static\" && move \"build\" \"deployment/static\""
}
Explanation:
The rm-rf equivalent for Windows (cmd.exe) is rd /s/q
The mv equivalent for Windows (cmd.exe) is move
All directory paths have been wrapped in escaped double quotes \"...\". For example;
deployment/static has been rewritten as \"deployment/static\".
Although escaped double quotes are not entirely necessary in this scenario, it's good practice and necessary to do this when paths may include spaces or punctuation characters.
The semi-colon ; has been replaced with the single & operator to ensure the react-script build part runs regardless of whether the initial rd /s/q ... command fails or succeeds.
The following error message would be printed to the console when using rd to delete a folder/path which may not exist:
The system cannot find the path specified
To prevent this error message from potentially being printed to the console we redirect the error message to NUL using the 2> nul part.
The md \"deployment/static\" part utilizes Windows md command to make the static directory - which is very similar to the mkdir command in bash.
Note: The above syntax will fail on nix based operating systems such as macOS and Linux.
Cross Platform Solution (Windows/Linux/macOS...)
To achieve a cross platform solution, (i.e. one which runs successfully on Windows, Linux, and macOS), I suggest writing two Nodejs utility scripts to substitute the rm -rf and mv bash commands. These two Nodejs scripts can then be invoked via your npm-script.
The following steps describe how this can be achieved.
Install shelljs which provides portable Unix shell commands for Nodejs. To do this, cd to your project directory an run the following command:
npm i -D shelljs
Create a new Nodejs script named rm.js with the following content:
rm.js
const shell = require('shelljs');
const args = process.argv.slice(2);
const dir = args[0];
shell.rm('-rf', dir);
Save this file in the root of your project directory, at the same level as where your projects package.json is stored.
Create a another Nodejs script named mv.js with the following content:
mv.js
const shell = require('shelljs');
const args = process.argv.slice(2);
const src = args[0];
const dest = args[1];
// Check src path has been provided and is valid
if (!src || !shell.test('-d', src)) {
console.log('\x1b[31m\x1b[40mERR!\x1b[0m src path cannot be found: %s', src);
process.exit(1);
}
// Check dest path has been provided.
if (!dest) {
console.log('\x1b[31m\x1b[40mERR!\x1b[0m dest path must be provided:');
process.exit(1);
}
// Make dest directory if necessary.
shell.mkdir('-p', dest);
// Move the file.
shell.mv(src, dest);
Also save this file in the root of your project directory, at the same level as where your projects package.json is stored.
Then configure your build script in package.json as follows:
"scripts": {
"build": "node rm \"deployment/static\" & react-scripts build && node mv \"build\" \"deployment/static\""
}
Note
The two utility scripts rm.js and mv.js are invoked in the npm-script named build via the parts reading; node rm ... and node mv ... respectively.
If you decide to store these two scripts in a different folder instead of the projects root directory, (as suggested in steps 2 and 3 previously), then you'll need to change the paths to the files. For example; if they were both saved in a folder named scripts which is located in the root of your project directory then your build script would be changed to:
"scripts": {
"build": "node scripts/rm \"deployment/static\" & react-scripts build && node scripts/mv \"build\" \"deployment/static\""
}
Edit / Update:
An alternative cross-platform solution, (which wasn't available when originally posting this answer), is to utilize the shx package, which is described as:
shx is a wrapper around ShellJS Unix commands, providing an easy solution for simple Unix-like, cross-platform commands in npm package scripts
Run the following command to install shx:
npm i -D shx
Then change your build script in package.json as follows:
"scripts": {
"build": "shx rm -rf deployment/static & react-scripts build && shx mv build deployment/static"
}

I use rimraf for this very reason.
Install it globally
npm i -g rimraf
and update your script as follows
"rimraf deployment/static;react-scripts build && mv build deployment/static"

The shx package should work very well; they even show rm -rf in the topmost package.json demo
Some of my coworkers use rimraf which is specifically the rm -rf unix command for node

for Windows:
in client folder
},
"scripts": {
"build-win": "react-scripts build && move build ..\\server\\public",
},
that will move folder to server folder

Related

How to hide variables in package.json

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.

Duplicating a React app folder does not work?

(This is on a Mac by the way. It seems cp -r on a Mac is "historical" and should be replaced by cp -R).
I tried the following:
mkdir TryContext
cd TryContext
npx create-react-app my-app
cd my-app
and then I made an app that worked, and npm start was able to start the server and run it.
But then if I want to make a version 2 of this app, and started by cloning the folder first:
cd ..
cp -r my-app my-app-02
to copy everything to my-app-02, and cd into that folder and do npm start, it will error, saying
> my-app#0.1.0 start /Users/username/code/TryContext/my-app-02
> react-scripts start
internal/modules/cjs/loader.js:800
throw err;
^
Error: Cannot find module '../scripts/start'
I tried different ways, and tried npm rebuild and then npm start, and it worked. But I thought if you copy a directory "as is", then using it, npm start should start the server without needing to do anything? Why was that and what ways besides npm rebuild could fix it?
TL;RD: when you copy using cp -r it doesn't really preserve symlinks, it just copies the file contents instead. So npm start can't find necessary symlink in this particular case. One of the possible solutions is to use cp -a when coping, which preserves symlinks and avoids this issue.
Mode detailed answer is here
:)

Multiple input-folders for uglifyjs?

I'm trying to set up an uglify task for npm for our AngularJS-project (OS Windows 10). It has several JS files in more than one folder beneath "src/main/webapp/app-basic-an/". It seems to me that I can't just write
"scripts": {
"uglify": "uglifyjs src/main/webapp/app-basic-an/*.js -m -o dist/js/app.js",
"preuglify": "rimraf dist && mkdir dist\\js"
}
cause that still requires all JS-files to be in the specified directory and doesn't include the subdirectories. Isn't there a way to say "include all JS-files beneath the folder src/main/webapp/app-basic-an/"?

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