简体   繁体   中英

Can't find static folder in express bundled by webpack (SSR)

I intend to do server side rendering in react with event handlers and I'm stuck on a problem on getting the index.js file be served in the localhost express server. Tried looking for several other answers here but I can't seem to wrap my head around this.

Here's the code.

import express from "express";
import React from "react";
import { renderToString } from "react-dom/server";
import App from "./app/home/app";
import path from "path";
import fs from "fs";

let server = port => {
  const app = express();

  app.use('/js', express.static(path.resolve('/static')));
  console.log(path.resolve('/static'));
  console.log(path.join(__dirname, '/static'));
  console.log(fs.existsSync(path.resolve('/static')));

  app.get("/", (req, res) => {
    res.status(200).send(renderMarkup(renderToString(<App />)));
  });

  app.get("/ping", (req, res) => {
    res.status(200).send("HELLO!");
  });

  app.listen(port, () => console.log("Server Ready!"));
}

let renderMarkup = html => {
  return `
    <!DOCTYPE html>
    <html>
        <head>
            <title>Webpack SSR Demo</title>
            <meta charset="utf-8" />
        </head>
        <body>
            <div id="app">${html}</div>
            <script src="/js/index.js"></script>
        </body>
    </html>
 `;
}

server(process.env.PORT || 8080);

I tried logging if my static directory exists. It returns a false although when I check my build folder (the output directory of the webpack bundle. It does exist).

My build folder directory is described below (rest assured all js bundles are built successfully):

build
|- static
|-- index.js
|- server.js

TLDR: The view is successfully rendered. The events are not working because the client side javascript is not being loaded.

After scouring a lot of questions, github issues and reading the bundled js.

It wasn't a problem with the server code. See: https://github.com/webpack/webpack/issues/1599

I needed to add this to my webpack.server.js:

node: {
  __dirname: false,
},

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM