[reactjs] 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.

This question is related to reactjs create-react-app

The answer is


Edit your package.json:

"build": "react-scripts build && mv build webapp"

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.


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

You can update the configuration with a little hack, under your root directory:

  1. npm run eject
  2. config/webpack.config.prod.js - line 61 - change path to: __dirname + './../--your directory of choice--'
  3. 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.


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).


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
.....

enter image description here

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'),
.....
}

enter image description here

Run

npm run build

Note: Running Platform dependent scripts are not advisable


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/....


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


webpack =>

renamed as build to dist

output: {
      filename: '[name].bundle.js',
      path: path.resolve(__dirname, 'dist'),
    },

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"

Quick compatibility build script (also works on Windows):

"build": "react-scripts build && rm -rf docs && mv build docs"

If you have arrived at this question three years after its initial posting because this is still a problem for you, consider backing this proposal to support a new BUILD_PATH environment variable.

https://github.com/facebook/create-react-app/pull/8986

From the proposal's documentation:

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.

If this proposal is adopted, it would mean that customizing the output target for create-react-app becomes as simple as updating updating your build script:

// 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'

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.


Examples related to reactjs

Error: Node Sass version 5.0.0 is incompatible with ^4.0.0 TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type string. Received type undefined raised when starting react app Template not provided using create-react-app How to resolve the error on 'react-native start' Element implicitly has an 'any' type because expression of type 'string' can't be used to index Invalid hook call. Hooks can only be called inside of the body of a function component How to style components using makeStyles and still have lifecycle methods in Material UI? React Hook "useState" is called in function "app" which is neither a React function component or a custom React Hook function How to fix missing dependency warning when using useEffect React Hook? Unable to load script.Make sure you are either running a Metro server or that your bundle 'index.android.bundle' is packaged correctly for release

Examples related to create-react-app

Error: Node Sass version 5.0.0 is incompatible with ^4.0.0 Template not provided using create-react-app How to fix missing dependency warning when using useEffect React Hook? What exactly is the 'react-scripts start' command? where is create-react-app webpack config and files? npm ERR! code UNABLE_TO_GET_ISSUER_CERT_LOCALLY Home does not contain an export named Home The create-react-app imports restriction outside of src directory Trying to use fetch and pass in mode: no-cors Can't build create-react-app project with custom PUBLIC_URL