How to serve static ReactJS files with expressJS?

Problem

I have successfully executed the index.html file of my React app, but index.js

that replaces <root>

in the html file with my first React component fails to run on ReactDOM.render

. How do I get the file index.js

to run? If my understanding of serving a React app gets skewed in a certain way, I would really appreciate the clarification.

Folder structure

  • / - contains all files on the server side including server.js

  • / client / - contains all React files
  • / client / build / - contains all ready-made client files
    • / client / build /index.html

    • / client / build / static / js / main.[hash].js

      - appears to be a mini version index.js

      that contains ReactDOM.render

      for my React app

Current deployment

  • I am using Facebook create-response app for / client / directory including npm run build to auto populate / client / build /

File fragments

// server.js
let app = express();
app.use(express.static(path.join(__dirname, '../client/public')));

      

This successfully loads the default index.html create react-app

// index.html
<body>
  <noscript>
    You need to enable JavaScript to run this app.
  </noscript>
  <div id="root"></div>
</body>

      

The above section of code may / may not be helpful, but it is the default html file that comes with create-react-app. Do I need to replace the noscript tag with a script tag that links to a minified index.js

file? I tried this and nothing changed, but it might be due to the wrong relative path.

+3


source to share


1 answer


After several trial / error attempts, the solution is pretty simple:

Serve in the / client / build directory in a static call like:



app.use(express.static(path.join(__dirname, '../client/build')));

      

+5


source







All Articles