Running create-react-app from non-root context path
1 min readApr 2, 2020
- Before building, set
PUBLIC_URL
env variable to the value of your subdirectory, let use/subdir
for example. You can also put this variable into your.env.production
(in case you do not have that file you can check the doc)
2. In public/index.html
add the base element bellow, this is for static files like images.
<base href="%PUBLIC_URL%/">
3. Also in public/index.html
, if you have custom link
element, make sure theyre are prefixed with %PUBLIC_URL%
(like manifest.json
and favicon.ico
href).
4. If you use BrowserRouter
, you can add basename
prop:
<BrowserRouter basename={process.env.PUBLIC_URL} />
5. If you use Router
instead, because you need access to history.push
method, to programmatically change page, do the following:
// history.tsx
import {createBrowserHistory} from 'history';export default createBrowserHistory({ basename: process.env.PUBLIC_URL });<!-- Where your router is, for me, App.tsx -->
<Router history={history}>
...
</Router>
6. Use relative links inside your elements
<!-- "./assets/quotes.png" is also ok, but "/assets/quotes.png" is not -->
<img src="assets/quotes.png" alt="" />
7. Move your background-image
links from scss to jsx/tsx files (note that you may not need to do that if you use css files):
/*remove that*/
background-image: url('/assets/background-form.jpg');<section style={{backgroundImage: `url('assets/background-form.jpg')`}}>
...