hack together preval plugin
This commit is contained in:
40
packages/docs-new/plugins/preval.ts
Normal file
40
packages/docs-new/plugins/preval.ts
Normal file
@@ -0,0 +1,40 @@
|
|||||||
|
import { unlink, writeFile } from "node:fs/promises"
|
||||||
|
import type { Plugin } from "vite"
|
||||||
|
import { transformWithEsbuild } from "vite"
|
||||||
|
|
||||||
|
const prevalPattern = /\.preval\.(js|ts|jsx|tsx|mts|cts)$/
|
||||||
|
|
||||||
|
export function preval(): Plugin {
|
||||||
|
return {
|
||||||
|
name: "preval",
|
||||||
|
enforce: "pre",
|
||||||
|
|
||||||
|
async transform(code, filePath) {
|
||||||
|
if (!prevalPattern.test(filePath)) return
|
||||||
|
|
||||||
|
const tempFilePath = `${filePath}.preval.mjs`
|
||||||
|
|
||||||
|
try {
|
||||||
|
const transformResult = await transformWithEsbuild(code, filePath, {
|
||||||
|
target: "node16",
|
||||||
|
format: "esm",
|
||||||
|
})
|
||||||
|
|
||||||
|
await writeFile(tempFilePath, transformResult.code)
|
||||||
|
const runResult = await import(tempFilePath)
|
||||||
|
|
||||||
|
const serialized = Object.entries(runResult)
|
||||||
|
.map(([key, value]) => {
|
||||||
|
return key === "default"
|
||||||
|
? `export default ${JSON.stringify(value)}`
|
||||||
|
: `export const ${key} = ${JSON.stringify(value)}`
|
||||||
|
})
|
||||||
|
.join("\n")
|
||||||
|
|
||||||
|
return serialized + "\n"
|
||||||
|
} finally {
|
||||||
|
await unlink(tempFilePath).catch(console.warn)
|
||||||
|
}
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -4,9 +4,13 @@ import react from "@vitejs/plugin-react"
|
|||||||
import remarkFrontmatter from "remark-frontmatter"
|
import remarkFrontmatter from "remark-frontmatter"
|
||||||
import { defineConfig } from "vite"
|
import { defineConfig } from "vite"
|
||||||
import ssr from "vite-plugin-ssr/plugin"
|
import ssr from "vite-plugin-ssr/plugin"
|
||||||
import xdm from "xdm/rollup"
|
import xdm from "xdm/rollup.js"
|
||||||
|
import { preval } from "./plugins/preval"
|
||||||
|
|
||||||
export default defineConfig({
|
export default defineConfig({
|
||||||
|
build: {
|
||||||
|
target: ["node16", "chrome89", "firefox89"],
|
||||||
|
},
|
||||||
plugins: [
|
plugins: [
|
||||||
ssr(),
|
ssr(),
|
||||||
react(),
|
react(),
|
||||||
@@ -14,6 +18,7 @@ export default defineConfig({
|
|||||||
remarkPlugins: [remarkFrontmatter],
|
remarkPlugins: [remarkFrontmatter],
|
||||||
rehypePlugins: [rehypePrism],
|
rehypePlugins: [rehypePrism],
|
||||||
}),
|
}),
|
||||||
|
preval(),
|
||||||
],
|
],
|
||||||
resolve: {
|
resolve: {
|
||||||
alias: {
|
alias: {
|
||||||
|
|||||||
Reference in New Issue
Block a user