Miao-Yunzai/src/utils/component.ts

53 lines
1.3 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'
2024-06-10 14:10:09 +08:00
export type ComponentCreateOpsionType = {
2024-06-10 09:34:28 +08:00
html_head?: string
html_name?: string
join_dir?: string
html_body?: string
2024-06-10 10:46:16 +08:00
file_create?: boolean
2024-06-10 09:34:28 +08:00
}
/**
* ************
*
* **********
*/
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>`
2024-06-10 10:46:16 +08:00
if (
typeof options?.file_create == 'boolean' &&
options?.file_create == false
) {
return html
}
2024-06-10 09:34:28 +08:00
writeFileSync(address, html)
return address
}
}