Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is it possible to access homepage from package.json in a react app?

I created a react app that will be served from /example-path. I defined it in the package.json like this:

"homepage":"/example-path"

It has worked so far, but now I would like to add routing with react-router-dom, and it incorrectly detects /example-path as the part of the URL.

This is my code:

<Router>
  <Switch>
    <Route path="/product/:id" children={<DisplayProduct />} />
  </Switch>
</Router>

Unfortunately react-router-dom tries to match the full URL /example-path/product/10. How is it possible to avoid that? Is it possible to access the homepage variable somehow?


I could use <Router basename="/example-path">, but in that way, this parameter is a duplicate. I would like to define it in only one place.

like image 578
Iter Ator Avatar asked Dec 22 '22 15:12

Iter Ator


2 Answers

How is it possible to access homepage from package.json in a react app?

We can access the URL set in package.json's homepage field using PUBLIC_URL environment variable.

We sometimes use a relative URL to deploy the application in subdirectories for example we are deploying the application in https://myhostname.com/example-path.

In order to do that, we can either set the environment variable PUBLIC_URL=/example-path for the application build or set the package.json homepage attribute to "/example-path". In your case, you have set the

"homepage": '/example-path/'

then the PUBLIC_URL would be set to /example-path/. Now you can access this environment variable anywhere in your react application.

<Router basename={process.env.PUBLIC_URL}>
  <Switch>
    <Route path="/product/:id" children={<DisplayProduct />} />
  </Switch>
</Router>

After running the npm run build, you can check in the build/index.html that all the places where you used the %PUBLIC_URL% is set to /example-path/ like below;

<script type="text/javascript" src="/example-path/static/js/main.ec7f1972.js">
like image 191
Subrato Pattanaik Avatar answered Jan 12 '23 00:01

Subrato Pattanaik


The Router doesn't know anything about your package.json. It just looks at the browser location. You can set a basename if you use BrowserRouter:

import {BrowserRouter as Router} from 'react-router';
<Router basename="/example-path">
    {/* ... */}
</Router>
like image 25
trixn Avatar answered Jan 11 '23 22:01

trixn