How do I use Express.js and Vanilla JS/HTML folder structure with Vite.js?

Viewed 415

I'm trying to setup Sever Side Rendering with Express.js and a Vanilla HTML and JS project but I don't know how, here is my folder structure. I want to see my home.html page by running the express server.

Test App
├── app
    ├── main.js
├── node_modules
├── html
    ├── home.html
├── package.json
├── package-lock.json
├── index.html
├── server.js

Here's what I've tried:

index.html

//... Default stuff
  <body>
    <div id="app"></div>
    <script type="module" src="/app/main.js"></script>
  </body>
//...

server.js

const fs = require("fs");
const path = require("path");
const express = require("express");
const { createServer: createViteServer } = require("vite");
const port = 3000;

async function createServer() {
    const app = express();

    const vite = await createViteServer({
        server: { middlewareMode: "ssr" },
    });
    app.use(vite.middlewares);

    app.use("*", async (req, res, next) => {
        const url = req.originalUrl;

        try {
            let template = fs.readFileSync(
                path.resolve(__dirname, "index.html"),
                "utf-8"
            );
         
            template = await vite.transformIndexHtml(url, template);

            const { render } = await vite.ssrLoadModule("/app/main.js");
 
            const appHtml = await render(url);

            const html = template.replace(`<!--ssr-outlet-->`, appHtml);

            res.status(200).set({ "Content-Type": "text/html" }).end(html);
        } catch (e) {
            vite.ssrFixStacktrace(e);
            next(e);
        }
    });

    app.listen(port, () => {
        console.log(`App listening on port ${port}`);
    });
}

createServer();

main.js

document.querySelector("#app").innerHTML = `
  <h1>Hello Vite!</h1>`;

package.json

{
  "name": "the-standard",
  "private": true,
  "version": "0.0.0",
  "scripts": {
    "dev": "nodemon server.js",
    "build": "vite build",
    "preview": "vite preview"
  },
  "devDependencies": {
    "vite": "^2.9.0"
  },
  "dependencies": {
    "express": "^4.17.3",
    "pug": "^3.0.2"
  }
}

And this is the error I get after I run npm run dev and refresh my page:

ReferenceError: document is not defined
at /app/main.js:3:1
at async instantiateModule (D:\Client Work\The Standard\node_modules\vite\dist\node\chunks\dep-611778e0.js:58364:9)
0 Answers
Related