2024-05-01 13:10:33 +00:00
|
|
|
import { join, resolve } from 'node:path'
|
|
|
|
import { promises as fsp } from 'node:fs'
|
2021-12-22 13:04:06 +00:00
|
|
|
import type { Plugin } from 'vite'
|
2024-05-01 20:42:12 +00:00
|
|
|
import { template } from 'lodash-es'
|
2021-12-22 13:04:06 +00:00
|
|
|
import genericMessages from '../templates/messages.json'
|
|
|
|
|
|
|
|
const r = (...path: string[]) => resolve(join(__dirname, '..', ...path))
|
|
|
|
|
|
|
|
export const DevRenderingPlugin = () => {
|
|
|
|
return <Plugin>{
|
|
|
|
name: 'dev-rendering',
|
|
|
|
async transformIndexHtml (html: string, context) {
|
|
|
|
const page = context.originalUrl || '/'
|
|
|
|
|
|
|
|
if (page === '/') {
|
|
|
|
const templateNames = await fsp.readdir(r('templates'))
|
|
|
|
const serializedData = JSON.stringify({ templateNames })
|
|
|
|
return html.replace('{{ data }}', serializedData)
|
|
|
|
}
|
|
|
|
|
|
|
|
const contents = await fsp.readFile(r(page, 'index.html'), 'utf-8')
|
|
|
|
|
|
|
|
const messages = JSON.parse(await fsp.readFile(r(page, 'messages.json'), 'utf-8'))
|
|
|
|
|
|
|
|
return template(contents, {
|
2024-05-01 13:10:33 +00:00
|
|
|
interpolate: /{{{?([\s\S]+?)}?}}/g,
|
2021-12-22 13:04:06 +00:00
|
|
|
})({
|
2024-05-01 13:10:33 +00:00
|
|
|
messages: { ...genericMessages, ...messages },
|
2021-12-22 13:04:06 +00:00
|
|
|
})
|
2024-05-01 13:10:33 +00:00
|
|
|
},
|
2021-12-22 13:04:06 +00:00
|
|
|
}
|
|
|
|
}
|