Miao-Yunzai/src/utils/component.ts

46 lines
1.2 KiB
TypeScript
Raw Normal View History

2024-06-10 09:34:28 +08:00
import React from 'react'
import { renderToString } from 'react-dom/server'
import { mkdirSync, writeFileSync } from 'fs'
import { join } from 'path'
type ComponentCreateOpsionType = {
html_head?: string
html_name?: string
join_dir?: string
html_body?: string
}
/**
* ************
*
* **********
*/
export class Component {
#dir = ''
constructor() {
this.#dir = join(process.cwd(), 'html')
mkdirSync(this.#dir, {
recursive: true
})
}
/**
*
* @param element
* @param name
* @returns
*/
create(element: React.ReactNode, options: ComponentCreateOpsionType) {
const str = renderToString(element)
2024-06-10 10:05:51 +08:00
const dir = join(this.#dir, options?.join_dir ?? '')
2024-06-10 09:34:28 +08:00
mkdirSync(dir, { recursive: true })
2024-06-10 10:05:51 +08:00
const address = join(dir, options?.html_name ?? 'hello.html')
2024-06-10 09:34:28 +08:00
const DOCTYPE = '<!DOCTYPE html>'
2024-06-10 10:05:51 +08:00
const Link = `<link rel="stylesheet" href="../public/output.css"></link>`
const head = `<head>${options?.html_head ?? Link}</head>`
const body = `<body> ${str} ${options?.html_body ?? ''}</body>`
2024-06-10 09:34:28 +08:00
const html = `${DOCTYPE}<html>${head}${body}</html>`
writeFileSync(address, html)
return address
}
}