Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(creator): exclude node_modules and dist during loading templates #9

Merged
merged 6 commits into from
Aug 24, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
/target
/node_modules
/dist
target
node_modules
dist
.vscode
2 changes: 1 addition & 1 deletion crates/metassr-build/src/server/manifest.rs
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ impl GlobalEntry {
{
Ok(Self {
head: PathBuf::from(head).canonicalize()?,
cache: PathBuf::from(cache).canonicalize()?,
cache: PathBuf::from(cache),
})
}
}
Expand Down
12 changes: 8 additions & 4 deletions crates/metassr-build/src/server/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ use metassr_utils::{
traits::AnalyzeDir,
};
use pages_generator::PagesGenerator;
use renderer::head::HeadRenderer;

use std::{
ffi::OsStr,
Expand Down Expand Up @@ -79,7 +80,6 @@ impl Build for ServerSideBuilder {
Err(e) => return Err(anyhow!("Couldn't generate targets: {e}")),
};


if let Err(e) = WebBundler::new(
&targets.ready_for_bundling(&self.dist_path),
&self.dist_path,
Expand All @@ -93,9 +93,13 @@ impl Build for ServerSideBuilder {
sleep(Duration::from_secs(1));
let dist = DistDir::new(&self.dist_path)?.analyze()?;

ManifestGenerator::new(targets.clone(), cache_dir.clone(), dist)
.generate(&head)?
.write(&self.dist_path)?;
let manifest =
ManifestGenerator::new(targets.clone(), cache_dir.clone(), dist).generate(&head)?;
manifest.write(&self.dist_path.clone())?;

if let Err(e) = HeadRenderer::new(&manifest.global.head, cache_dir.clone()).render(true) {
return Err(anyhow!("Coludn't render head: {e}"));
}

if self.building_type == BuildingType::StaticSiteGeneration {
if let Err(e) =
Expand Down
2 changes: 1 addition & 1 deletion crates/metassr-build/src/server/pages_generator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ impl PagesGenerator {
cache_dir: CacheDir,
) -> Result<Self> {
let dist = DistDir::new(dist_path)?.analyze()?;
let head = HeadRenderer::new(&head_path, cache_dir.clone()).render()?;
let head = HeadRenderer::new(&head_path, cache_dir.clone()).render(true)?;
let cache = cache_dir.dir_path();

let output = MultiRenderExec::new(targets.ready_for_exec())?.exec()?;
Expand Down
41 changes: 23 additions & 18 deletions crates/metassr-build/src/server/renderer/head.rs
Original file line number Diff line number Diff line change
Expand Up @@ -51,37 +51,42 @@ impl HeadRenderer {
}
}

pub fn render(&mut self) -> Result<String> {
let script = format!(
r#"
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()
);

"#,
self.path.canonicalize()?.display()
);

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

if !IS_HEAD_SCRIPT_LOADED.lock().unwrap().is_loaded() {
let mut name = path.clone();
name.set_extension("");
let name = name.to_str().unwrap().to_string();
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 fullpath = path.canonicalize()?.to_str().unwrap().to_string();

let target = HashMap::from([(name, fullpath)]);
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}"));
}
if let Err(e) = WebBundler::new(&target, &self.cache_dir.dir_path()).exec() {
return Err(anyhow!("Cannot bundling head: {e}"));
}

// TODO: remove this line
sleep(Duration::from_millis(500));
// TODO: remove this line
sleep(Duration::from_millis(500));
}

let _ = loaders::from_single_file(
"node",
Expand Down
2 changes: 1 addition & 1 deletion crates/metassr-build/src/server/renderer/page.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ impl PageRenderer {

let exec = RenderExec::new(entry.id, &entry.renderer)?;
let body = exec.exec()?;
let head = HeadRenderer::new(&manifest.global.head, cache).render()?;
let head = HeadRenderer::new(&manifest.global.head, cache).render(false)?;

Ok(Self {
head,
Expand Down
10 changes: 2 additions & 8 deletions crates/metassr-build/src/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,15 +6,9 @@ use std::{
pub fn setup_page_path(page: &str, ext: &str) -> PathBuf {
match Path::new(page) {
path if path.file_stem() != Some(OsStr::new("index")) => {
let mut path = path.to_path_buf();
path.set_extension("");
path.join(format!("index.{ext}"))
path.to_path_buf().with_extension("").join(format!("index.{ext}"))
}

path => {
let mut path = path.to_path_buf();
path.set_extension(ext);
path
}
path => path.to_path_buf().with_extension(ext),
}
}
5 changes: 5 additions & 0 deletions crates/metassr-create/build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,11 @@ fn main() {
.into_iter()
.filter_map(Result::ok)
.filter(|e| e.file_type().is_file())
.filter(|e| {
!e.path().components().any(|component| {
component.as_os_str() == "node_modules" || component.as_os_str() == "dist"
})
})
{
let path = entry.path();
let relative_path = path.strip_prefix(templates_dir).unwrap().to_str().unwrap();
Expand Down
15 changes: 4 additions & 11 deletions crates/metassr-create/templates/javascript/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,21 +5,14 @@
"scripts": {
"run": "metassr-cli --debug-mode=http run",
"build:ssr": "metassr-cli --debug-mode=metacall build -t ssr",
"serve:ssg": "metassr-cli --debug-mode=http run --serve",
"build:ssg": "metassr-cli --debug-mode=metacall build -t ssg",
"dev": "rspack --watch"
"serve": "metassr-cli --debug-mode=http run --serve",
"build:ssg": "metassr-cli --debug-mode=metacall build -t ssg"
},
"devDependencies": {
"@rspack/cli": "^0.7.5",
"@rspack/core": "^0.7.5",
"@swc/cli": "^0.3.12",
"@swc/core": "^1.4.16",
"@swc/helpers": "^0.5.11",
"@types/react": "^18.0.24",
"@types/react-dom": "^18.0.8"
"@rspack/core": "^0.7.5"
},
"dependencies": {
"react": "^18.3.1",
"react-dom": "^18.3.1"
}
}
}
6 changes: 0 additions & 6 deletions crates/metassr-create/templates/typescript/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,13 +10,7 @@
"dev": "rspack --watch"
},
"devDependencies": {
"@rspack/cli": "^0.7.5",
"@rspack/core": "^0.7.5",
"@swc/cli": "^0.3.12",
"@swc/core": "^1.4.16",
"@swc/helpers": "^0.5.11",
"@types/react": "^18.0.24",
"@types/react-dom": "^18.0.8"
},
"dependencies": {
"react": "^18.3.1",
Expand Down
6 changes: 5 additions & 1 deletion crates/metassr-utils/src/cache_dir.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
use anyhow::Result;
use std::{
collections::HashMap, ffi::OsStr, fs::{self, File}, io::{Read, Write}, path::{Path, PathBuf}
collections::HashMap,
ffi::OsStr,
fs::{self, File},
io::{Read, Write},
path::{Path, PathBuf},
};
use walkdir::WalkDir;

Expand Down
16 changes: 8 additions & 8 deletions metassr-cli/src/cli/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ Command line interface application for MetaSSR framework. This CLI tool helps yo
)]
pub struct Args {
/// The path of the project root directory.
#[arg(long)]
#[arg(long, default_value_t = String::from("."))]
pub root: String,

/// Enable debug mode to provide more detailed logs.
Expand All @@ -31,7 +31,7 @@ pub struct Args {
pub log_file: Option<String>,

#[command(subcommand)]
pub commands: Option<Commands>,
pub commands: Commands,
}

#[derive(Debug, ValueEnum, PartialEq, Eq, Clone)]
Expand All @@ -49,18 +49,18 @@ pub enum Commands {
/// Builds your web application into a deployable format.
Build {
/// The output directory where build files will be saved.
#[arg(long)]
#[arg(long, default_value_t = String::from("dist"))]
out_dir: String,

/// The type of build to perform. Choose between SSR (Server-Side Rendering) and SSG (Static Site Generation).
#[arg(short = 't', long = "type")]
#[arg(short = 't', long = "type", default_value_t = BuildingType::SSR)]
build_type: BuildingType,
},

/// Runs the Server-Side Rendered (SSR) application.
Run {
/// The port number on which the HTTP server will run.
#[arg(long)]
#[arg(long, default_value_t = 8080)]
port: u16,

/// Serve the generated static site directly.
Expand All @@ -75,15 +75,15 @@ pub enum Commands {
project_name: String,

/// The version of your web application.
#[arg(long, short)]
#[arg(long, short, default_value_t = String::from("1.0.0"))]
version: String,

/// A brief description of your web application.
#[arg(long, short)]
#[arg(long, short, default_value_t = String::from("A web application built with MetaSSR framework"))]
description: String,

/// The template to use for creating the new project.
#[arg(long, short)]
#[arg(long, short, default_value_t = Template::Javascript)]
template: Template,
},
}
14 changes: 6 additions & 8 deletions metassr-cli/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ async fn main() -> Result<()> {
[Some(DebugMode::All), Some(DebugMode::Metacall)].contains(&args.debug_mode);
let allow_http_debug = [Some(DebugMode::All), Some(DebugMode::Http)].contains(&args.debug_mode);

if let Some(Commands::Create { .. }) = args.commands {
if let Commands::Create { .. } = args.commands {
tracing_subscriber::fmt()
.with_target(false)
.without_time()
Expand All @@ -45,28 +45,26 @@ async fn main() -> Result<()> {
set_var("METACALL_DEBUG", "1");
}
}

match args.commands {
Some(Commands::Build {
Commands::Build {
out_dir,
build_type,
}) => {
} => {
cli::Builder::new(build_type, out_dir).exec()?;
}
Some(Commands::Run { port, serve }) => {
Commands::Run { port, serve } => {
cli::Runner::new(port, serve, allow_http_debug)
.exec()
.await?;
}
Some(Commands::Create {
Commands::Create {
project_name,
version,
description,
template,
}) => {
} => {
cli::Creator::new(project_name, version, description, template).exec()?;
}
_ => {}
};

Ok(())
Expand Down
10 changes: 4 additions & 6 deletions tests/web-app/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,19 +4,17 @@
"description": "",
"main": "App.tsx",
"scripts": {
"build": "node scripts/build.js"
"build": "../../target/debug/metassr-cli --debug-mode=metacall build",
"build:ssg": "../../target/debug/metassr-cli --debug-mode=metacall build -t ssg",
"run": "../../target/debug/metassr-cli --debug-mode=metacall run ",
"run:ssg": "../../target/debug/metassr-cli --debug-mode=metacall run --serve"
},
"devDependencies": {
"@swc/cli": "^0.3.12",
"@swc/core": "^1.4.16",
"@swc/helpers": "^0.5.11",
"@types/react": "^18.0.24",
"@types/react-dom": "^18.0.8"
},
"dependencies": {
"typescript": "^4.6.4",
"react": "^18.3.1",
"@rspack/core": "^0.7.5",
"react-dom": "^18.3.1"
}
}
Loading