diff --git a/src/node/cli.ts b/src/node/cli.ts index 36ed973..84e57ac 100644 --- a/src/node/cli.ts +++ b/src/node/cli.ts @@ -1,4 +1,4 @@ -import path = require("path"); +import * as path from "path"; import { cac } from "cac"; import { createDevServer } from "./dev"; diff --git a/src/node/constant/index.ts b/src/node/constant/index.ts new file mode 100644 index 0000000..e148fc4 --- /dev/null +++ b/src/node/constant/index.ts @@ -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"); \ No newline at end of file diff --git a/src/node/dev.ts b/src/node/dev.ts index 96aa3ec..d56c3ff 100644 --- a/src/node/dev.ts +++ b/src/node/dev.ts @@ -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()] }) } diff --git a/src/node/plugin-r-press/indexHtml.ts b/src/node/plugin-r-press/indexHtml.ts new file mode 100644 index 0000000..71e5f7b --- /dev/null +++ b/src/node/plugin-r-press/indexHtml.ts @@ -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); + } + }) + } + } +} \ No newline at end of file diff --git a/template.html b/template.html new file mode 100644 index 0000000..8e6061e --- /dev/null +++ b/template.html @@ -0,0 +1,14 @@ + + + + + + + Document + + + +
running~
+ + + \ No newline at end of file