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'),
},
Related
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.
I have a lerna + yarn workspaces monorepo which uses storybook.
Each package/component has its own /assets folder containing static images as following:
/packages
/component1
/assets
... static images
index.tsx
/component2
/assets
... static images
index.tsx
in the official documentation it says to include -s option but it suits only for a single general assets folder, not per package:
start-storybook -p 6006 -s assets
how can I serve those static assets in storybook for each component?
You can specify multiple static directories if you split them via a , as documented here.
Plus you can also specify a path to serve it at if you split the source location and the path location with a :, undocumented, but you can have a look at this split call in the source code here.
Putting this together in this instance, you could run
"scripts" {
"storybook": "start-storybook -s ./packages/component1/assets:assets,./packages/component2/assets:assets"
}
well.. it seems that it is not supported out-of-the-box so this is my solution to the problem, hope it will help other people.
the basic idea is to copy all the static assets of all the packages into the storybook output directory:
package.json
"scripts": {
// build the storybook and run copy assets script
"build-storybook": "build-storybook -c .storybook -o .out && yarn copy-storybook-assets",
// clean output directory, copy the assets to the output directory and run the storybook
"dev": "yarn clean-storybook-output && yarn copy-storybook-assets && start-storybook -p 6006 -s .out",
// clean the output directory
"clean-storybook-output": "rimraf .out",
// run on all the packages and copy all the static assets to the output directory
"copy-storybook-assets": "copyfiles -f \"packages/**/assets/*\" -u 1 .out"
},
I've learned about pipelines with bitbucket and I want to make a new one to upload my react application (bootstrapped with create-react-app) and uploaded to an Amazon S3 bucket.
I made a bitbucket-pipelines.yml file like this one
image: node:10.15.3
pipelines:
default:
- step:
name: Installing dependencies
caches:
- node
script: # Modify the commands below to build your repository.
- rm -rf package-lock.json
- rm -f node_modules
- yarn add
- step:
name: Build
script:
- yarn build
When Bitbucket runs it, it shows me the next error message
env-cmd -f .env.production.local react-scripts build
Error: Unable to locate env file at location (.env.production.local)
This is it because in my package.json I use env-cmd to read my environment variables for the building script.
"scripts": {
"start": "env-cmd -f .env.development.local react-scripts start",
"build": "env-cmd -f .env.production.local react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
But I don't know how to read that environment variables (localized inside of my .env files) in my bitbucket-pipelines.yml file
How can I get that?
Better late than never...
.env, .env.production.local, or whatever file name you want. Interchangable.
first encode you .env file:
base64 -w 0 .env > envout.txt
Then add the contents of envout.txt to a repository variable in bitbucket $ENV_ENCODED or similar
Add decode command to your pipeline:
echo $ENV_ENCODED | base64 -d > .env
Extra info:
this needs to be done as one step, so include it just before your build
if the command is not found, use build image with base64
Other option is to include .env in docker image that you host on a secure service like AWS ECR and pull the image from there, and it will have your .env file
If someone is able to download build agent as artifact, they will be able to view the contents of your .env. This is more of a deterrent than the most secure option.
adding - cat .env as a step would validate the process, but maybe use fake .env
I would also recommend doing your installation and build in the same step. I've ran into issues where generated files (especially .env) are different between steps.
image: node:10.15.3
pipelines:
default:
- step:
name: Installing dependencies and Build
caches:
- node
script: # Modify the commands below to build your repository.
- rm -rf package-lock.json
- rm -f node_modules
- yarn add
- echo $ENV_ENCODED | base64 -d > .env
- yarn build
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/"?
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