Have you ever tried to deploy your React App to a subdirectory like
http://my-website.com/my-new-app/
or even a local file path like
file:///android_asset/my-embedded-app/
and were stuck with a blank screen?
I was just recently.
The reason for this can easily be found by inspecting the web page. You will see error messages like a needed resource
*.chunk.1234.js
could not be loaded.
Reason: wrong include path.
By default, the react-app will be built in a way that resources are linked absolute, beginning with a forward-slash /
. So if you try to deploy your app to something like http://my-website.com/my-new-app/
it will not work because your app will request assets from http://my-website.com/
instead of your my-new-app
sub-directory.
The Fix
React-side
Go to your package.json
and add the following line:
"homepage": "."
What does it do? During the build, it handles all paths as if they were related to your current directory. So as soon as you load your index.html
, all static files are linked relatively to your index.html
.
Unfortunately, if you have a funky custom routing system, this approach could not work for you. If you use react-router, it could be mandatory to set a basepath
that matches your desired sub-directory depending on the router implementation you might use.
Web-Server
Keep in mind that you also have to configure your web server correctly:
// nginx
server {
server_name my-website.com;
...
location ~ /my-new-app {
root ...;
try_files $uri /my-new-app/index.html;
}
}
References
- Logo in the header image: React JS Logo, License: Attribution 4.0 International