Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to bundle a React app to work in ANY subdirectory on a server?

This SO thread explains how to bundle a react app for deployment to a specific subdirectory on a web server. I would like to bundle my react app to work on any subdirectory on my webserver. In other words: Is it possible to build a react app, such that I can move it from

http://server/foo

to

http://server/bar

or

http://server/foo/bar

without rebuilding or changing anything?

like image 901
Marc Avatar asked Oct 28 '22 09:10

Marc


2 Answers

If you are using react-router-dom, If you know your directory name you could set basename to "/directory-name" in the router

or

If you want to set the base name to be dynamic, use

(Note: This won't be useful if you are using sub routing)

or

Incase of sub routing, set a standard string to your routes

Example:

 let basename_path = null;
   var url = window.location.pathname.toLowerCase();
   if(url.indexOf("react") === -1){    // If string(react) not available
            basename_path = "/";
   }
    else{
       var array = url.split("react");
       basename_path = array[0]+"react/";
     }


 <Router basename={basename_path}>   
   <Route exact path="/react/home" component={home}/>
   <Route exact path="/react/contactus" component={contactus}/>
   <Route exact path="/react/aboutus" component={aboutus}/>               
 </Router> 
like image 195
Pavan Kumar Velpula Avatar answered Nov 15 '22 11:11

Pavan Kumar Velpula


in package.json

"homepage": ".",
like image 30
Kani Avatar answered Nov 15 '22 13:11

Kani