Skip to content

Commit

Permalink
feat: render index html
Browse files Browse the repository at this point in the history
  • Loading branch information
c0dedance committed Oct 12, 2023
1 parent 4200d39 commit 1f3a4c5
Show file tree
Hide file tree
Showing 5 changed files with 50 additions and 1 deletion.
2 changes: 1 addition & 1 deletion src/node/cli.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import path = require("path");
import * as path from "path";
import { cac } from "cac";
import { createDevServer } from "./dev";

Expand Down
5 changes: 5 additions & 0 deletions src/node/constant/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import * as path from "path";

export const ROOT = path.resolve(__dirname, "../../../");

export const DEFAULT_HTML_PATH = path.resolve(ROOT, "template.html");
2 changes: 2 additions & 0 deletions src/node/dev.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
import { createServer as createViteDevServer } from "vite";
import { pluginIndexHtml } from "./plugin-r-press/indexHtml";


export function createDevServer(root: string = process.cwd()) {
return createViteDevServer({
root,
plugins: [pluginIndexHtml()]
})
}
28 changes: 28 additions & 0 deletions src/node/plugin-r-press/indexHtml.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import { readFile } from "fs/promises";
import { Plugin } from "vite";
import { DEFAULT_HTML_PATH } from "../constant";


export function pluginIndexHtml(): Plugin {
return {
name: 'r-press:index-html',
// 不在函数题体直接插入中间件,而是在configureServer中插入?
// 防止影响vite的逻辑
configureServer(server) {
server.middlewares.use(async (req, res, next) => {
if (req.url !== '/') {
return next();
}
const htmlContent = await readFile(DEFAULT_HTML_PATH, 'utf-8');

try {
res.statusCode = 200;
res.setHeader("Content-Type", "text/html");
res.end(htmlContent);
} catch (e) {
return next(e);
}
})
}
}
}
14 changes: 14 additions & 0 deletions template.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>

<body>
<div id="root">running~</div>
</body>

</html>

0 comments on commit 1f3a4c5

Please sign in to comment.