|
| 1 | +/* eslint-disable @typescript-eslint/no-var-requires */ |
1 | 2 | import child from "child_process";
|
2 | 3 | import fs from "fs/promises";
|
| 4 | +import path from "path"; |
3 | 5 | import React from "react";
|
4 | 6 | import ReactDOMServer from "react-dom/server";
|
5 | 7 | import { promisify } from "util";
|
6 | 8 |
|
7 |
| -import App from "./app"; |
8 |
| - |
9 | 9 | const exec = promisify(child.exec);
|
10 | 10 |
|
| 11 | +const appPath = path.resolve(__dirname, "./app.tsx"); |
| 12 | +const entryPath = path.resolve(__dirname, "./entry.tsx"); |
| 13 | +require.extensions[".less"] = () => undefined; |
| 14 | + |
11 | 15 | (async () => {
|
12 |
| - const HTML = ReactDOMServer.renderToString(React.createElement(App)); |
| 16 | + const distPath = path.resolve("./dist"); |
| 17 | + const tempPath = path.resolve("./.temp"); |
| 18 | + await fs.mkdir(distPath, { recursive: true }); |
| 19 | + await fs.mkdir(tempPath, { recursive: true }); |
| 20 | + |
| 21 | + await exec(`npx rspack -c ./rspack.server.ts`); |
| 22 | + const nodeSideAppPath = path.resolve(tempPath, "node-side-entry.js"); |
| 23 | + const nodeSideApp = require(nodeSideAppPath); |
| 24 | + const App = nodeSideApp.default; |
| 25 | + const getStaticProps = nodeSideApp.getStaticProps; |
| 26 | + let defaultProps = {}; |
| 27 | + if (getStaticProps) { |
| 28 | + defaultProps = await getStaticProps(); |
| 29 | + } |
| 30 | + |
| 31 | + const entry = await fs.readFile(entryPath, "utf-8"); |
| 32 | + const tempEntry = entry |
| 33 | + .replace("<props placeholder>", JSON.stringify(defaultProps)) |
| 34 | + .replace("<index placeholder>", appPath); |
| 35 | + await fs.writeFile(path.resolve(tempPath, "client-side-entry.tsx"), tempEntry); |
| 36 | + |
| 37 | + const HTML = ReactDOMServer.renderToString(React.createElement(App, defaultProps)); |
13 | 38 | const template = await fs.readFile("./public/index.html", "utf-8");
|
14 | 39 | const random = Math.random().toString(16).substring(7);
|
15 |
| - const path = "./dist/"; |
16 | 40 | await exec(`npx rspack build -- --output-filename=${random}`);
|
17 |
| - const jsPathName = `${random}.js`; |
| 41 | + const jsFileName = `${random}.js`; |
| 42 | + |
18 | 43 | const html = template
|
19 | 44 | .replace(/<!-- INJECT HTML -->/, HTML)
|
20 |
| - .replace(/<!-- INJECT SCRIPT -->/, `<script src="${jsPathName}"></script>`); |
21 |
| - await fs.writeFile(`${path}index.html`, html); |
| 45 | + .replace(/<!-- INJECT STYLE -->/, `<link rel="stylesheet" href="${random}.css">`) |
| 46 | + .replace(/<!-- INJECT SCRIPT -->/, `<script src="${jsFileName}"></script>`); |
| 47 | + await fs.writeFile(path.resolve(distPath, "index.html"), html); |
22 | 48 | })();
|
0 commit comments