0
votes

Hi I am new developer at CRA. I have a project and I had created it with create react app. When I use run npm run build, It can not set home page which has only a button for test. I added react-router-dom and homepage:"./" in my package.json. In localhost I can use and see everything correctly but when try it with npm run build , I can't reach anything and build shows me empty page. What should I do? Do you have an advice to me ? I dont know anything whether everything works correctly.

App.Tsx:

 import React from 'react';
    import { Route, Switch,BrowserRouter } from 'react-router-dom';
    import HomeDashboard from './containers/Home' 
    
    function App() {
      return (
        <div className="App">
          <BrowserRouter>
          <Switch>
            <Route exact path="/home" component={HomeDashboard}></Route>
            <Route exact path="/" component={HomeDashboard}></Route>
          </Switch>
          </BrowserRouter>
        </div>
      );
    }
    export default App;

package.json :

 {
      "name": "test",
      "version": "0.1.0",
      "private": true,
      "homepage": "./",
      "dependencies": {
        "@types/react-dom": "^16.9.8",
        "@types/react-router-dom": "^5.1.5",
        "react": "^16.13.1",
        "react-dom": "^16.13.1",
        "react-router-dom": "^5.2.0",
        "react-scripts": "3.4.3",
        "typescript": "^3.9.7"
      },
      "scripts": {
        "build": "react-scripts build",
      },
      "eslintConfig": {
        "extends": "react-app"
      },
      
    }

build folder: enter image description here

2
I think this is because you need to serve it to see it properly - marsnebulasoup
Try installing serve with npm install -g serve and then serve your build directory with serve -s build - marsnebulasoup

2 Answers

2
votes

This is expected. Your built index.html refers to all javascript and css files by an absolute link, which will not work if you just open it on your machine. You have to serve it from a server. Locally you could use the serve npm package for that:

npm install -g serve
cd ./build
serve .
1
votes

The npm run build command simply compiles your react application to pure html, javascript, css.
It does not serve it on your localhost or somewhere else. You can see the built app by opening the /build/index.html with a browser, but this may not work due to realtive paths, routing and cors policies.

You can follow the instructions in the docs and use serve to serve it: https://create-react-app.dev/docs/deployment/