Skip to content

Commit

Permalink
refactor(builder): make head rendering more clean
Browse files Browse the repository at this point in the history
  • Loading branch information
hulxv committed Aug 24, 2024
1 parent d691fa7 commit a5dd438
Showing 1 changed file with 32 additions and 30 deletions.
62 changes: 32 additions & 30 deletions crates/metassr-build/src/server/renderer/head.rs
Original file line number Diff line number Diff line change
Expand Up @@ -54,36 +54,7 @@ impl HeadRenderer {
pub fn render(&mut self, bundler: bool) -> Result<String> {
if !IS_HEAD_SCRIPT_LOADED.lock().unwrap().is_loaded() {
if bundler {
let script = format!(
r#"
import Head from "{}"
import {{ renderToString }} from "react-dom/server"
import React from "react"
export function render_head() {{
return renderToString(<Head />);
}}
"#,
self.path.canonicalize()?.display()
);

let path = self.cache_dir.insert("head.js", script.as_bytes())?;

let name = PathBuf::from(path.clone().file_name().unwrap())
.with_extension("")
.to_str()
.unwrap()
.to_string();

let fullpath = path.canonicalize()?.to_str().unwrap().to_string();

let target = HashMap::from([(name, fullpath)]);

if let Err(e) = WebBundler::new(&target, &self.cache_dir.dir_path()).exec() {
return Err(anyhow!("Cannot bundling head: {e}"));
}

self.bundle()?;
// TODO: remove this line
sleep(Duration::from_millis(500));
}
Expand All @@ -99,4 +70,35 @@ export function render_head() {{
Ok(out) => Ok(out),
}
}

fn bundle(&mut self) -> Result<()> {
let script = format!(
r#"
import Head from "{}"
import {{ renderToString }} from "react-dom/server"
import React from "react"
export function render_head() {{
return renderToString(<Head />);
}}
"#,
self.path.canonicalize()?.display()
);

let path = self.cache_dir.insert("head.js", script.as_bytes())?;
let name = PathBuf::from(path.clone().file_name().unwrap())
.with_extension("")
.to_str()
.unwrap()
.to_string();
let fullpath = path.canonicalize()?.to_str().unwrap().to_string();

let target = HashMap::from([(name, fullpath)]);

if let Err(e) = WebBundler::new(&target, &self.cache_dir.dir_path()).exec() {
return Err(anyhow!("Cannot bundling head: {e}"));
}
Ok(())
}
}

0 comments on commit a5dd438

Please sign in to comment.