Skip to content

Commit

Permalink
Various fixes (#66)
Browse files Browse the repository at this point in the history
* More biome tweaks, fix config file formatting

* Remove unnecessary layout from vike setup

* Improve binary size, other fixes
  • Loading branch information
willcrichton authored Jul 1, 2024
1 parent c08ac3a commit f46196f
Show file tree
Hide file tree
Showing 4 changed files with 51 additions and 45 deletions.
7 changes: 6 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,3 +1,8 @@
[workspace]
resolver = "2"
members = ["crates/*"]
members = ["crates/*"]

[profile.release]
strip = true
lto = true
opt-level = "z"
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ Alternatively, you can follow one of these installation methods:

```
cargo install depot-js --locked
depot setup
```

### From source
Expand All @@ -46,6 +47,7 @@ cargo install depot-js --locked
git clone https://github.com/cognitive-engineering-lab/depot
cd depot
cargo install --path crates/depot --locked
depot setup
```

## Usage
Expand Down
74 changes: 30 additions & 44 deletions crates/depot/src/commands/new.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
#![allow(clippy::items_after_statements, clippy::too_many_lines)]

use anyhow::{ensure, Result};
use anyhow::{ensure, Context, Result};
use indexmap::{indexmap, IndexMap};
use package_json_schema as pj;
use serde_json::{json, Value};
Expand All @@ -11,6 +11,7 @@ use std::{
io::{BufReader, Seek, Write},
path::{Path, PathBuf},
process::Command,
str::FromStr,
};

use crate::{
Expand Down Expand Up @@ -297,24 +298,21 @@ impl NewCommand {
fn make_biome_config(&self) -> Result<FileVec> {
let mut config = json!({
"$schema": "https://biomejs.dev/schemas/1.8.2/schema.json",
"organizeImports": {
"enabled": true
},
"javascript": {
"formatter": {
"arrowParentheses": "asNeeded"
"arrowParentheses": "asNeeded",
"trailingCommas": "none"
}
},
"formatter": {
"enabled": true,
"indentStyle": "space"
},
"linter": {
"enabled": true,
"rules": {
"recommended": true,
"correctness": {"noUnusedImports": "warn"},
"style": {"noNonNullAssertion": "off", "useConst": "off"}
"style": {"noNonNullAssertion": "off", "useConst": "off", "noUselessElse": "off"},
"complexity": { "noBannedTypes": "off", "noForEach": "off" },
}
}
});
Expand All @@ -328,7 +326,7 @@ impl NewCommand {
},
"linter": {
"rules": {
"correctness": {"useExhaustiveDependencies": "off"},
"correctness": {"useExhaustiveDependencies": "off", "useJsxKeyInIterable": "off"},
"suspicious": {"noArrayIndexKey": "off"}
}
}
Expand Down Expand Up @@ -358,7 +356,7 @@ impl NewCommand {
""
};

let mut imports = vec![("fs", "fs")];
let mut imports = vec![("fs", "node:fs")];
if self.args.react {
imports.push(("react", "@vitejs/plugin-react"));
}
Expand All @@ -367,10 +365,6 @@ impl NewCommand {
}
imports.push(("{ defineConfig }", "vite"));

if platform.is_node() {
imports.push(("{ builtinModules }", "module"));
}

let mut config: Vec<(&str, Cow<'static, str>)> = Vec::new();

match target {
Expand All @@ -380,23 +374,23 @@ impl NewCommand {
}
}
Target::Script => {
imports.push(("{ resolve }", "path"));
imports.push(("{ resolve }", "node:path"));
let build_config = match platform {
Platform::Browser => {
let name = self.args.name.as_global_var();
format!(
r#"lib: {{
entry: resolve(__dirname, "src/{}"),
name: "{name}",
formats: ["iife"],
formats: ["iife"]
}},"#,
entry_point.unwrap()
)
}
Platform::Node => format!(
r#"lib: {{
entry: resolve(__dirname, "src/{}"),
formats: ["cjs"],
entry: resolve(__dirname, "src/{}"),
formats: ["cjs"]
}},
minify: false,"#,
entry_point.unwrap()
Expand All @@ -405,6 +399,7 @@ minify: false,"#,

let mut external = "Object.keys(manifest.dependencies || {})".to_string();
if platform.is_node() {
imports.push(("{ builtinModules }", "node:module"));
external.push_str(".concat(builtinModules)");
}

Expand All @@ -427,7 +422,7 @@ minify: false,"#,
config.push((
"define",
r#"{
"process.env.NODE_ENV": JSON.stringify(mode),
"process.env.NODE_ENV": JSON.stringify(mode)
}"#
.into(),
));
Expand All @@ -449,29 +444,32 @@ minify: false,"#,
r#"{{
environment: "{environment}",{setup_files}
deps: {{
inline: [/^(?!.*vitest).*$/],
}},
inline: [/^(?!.*vitest).*$/]
}}
}}"#
);
config.push(("test", test_config.into()));

if platform.is_node() {
config.push(("resolve", "{conditions: [\"node\"]}".into()));
config.push(("resolve", "{ conditions: [\"node\"] }".into()));
}

imports.sort_by_cached_key(|(_, path)| PackageName::from_str(path).unwrap());
let imports_str = imports
.into_iter()
.map(|(l, r)| format!("import {l} from \"{r}\";\n"))
.collect::<String>();
let config_str = config
.into_iter()
.map(|(k, v)| textwrap::indent(&format!("{k}: {v},\n"), " "))
.collect::<String>();
.map(|(k, v)| textwrap::indent(&format!("{k}: {v}"), " "))
.collect::<Vec<String>>()
.join(",\n");
let mut src = format!(
r#"{imports_str}
let manifest = JSON.parse(fs.readFileSync("package.json", "utf-8"));
export default defineConfig(({{ mode }}) => ({{
{config_str}}}));
{config_str}
}}));
"#
);

Expand Down Expand Up @@ -516,10 +514,12 @@ export default defineConfig(({{ mode }}) => ({{
}

fn update_typedoc_config(&self, ws: &Workspace) -> Result<()> {
let path = ws.root.join("typedoc.json");
let mut f = OpenOptions::new()
.read(true)
.write(true)
.open(ws.root.join("typedoc.json"))?;
.open(&path)
.with_context(|| format!("Failed to open file: {}", path.display()))?;
let mut config: Value = {
let reader = BufReader::new(&mut f);
serde_json::from_reader(reader)?
Expand Down Expand Up @@ -712,35 +712,21 @@ export default defineConfig(({{ mode }}) => ({{

dev_dependencies.push("normalize.css");

let css_path = if self.args.sass {
"index.scss"
} else {
"index.css"
};
let css_name = if self.args.vike { "base" } else { "index" };
let css_path = format!("{css_name}.{}", if self.args.sass { "scss" } else { "css" });

if self.args.vike {
ensure!(self.args.react, "Currently must use --react with --vike");
const CONFIG_SRC: &str = r#"import vikeReact from "vike-react/config";
import type { Config } from "vike/types";
import { Layout } from "./Layout";
export let config: Config = {
Layout,
extends: vikeReact,
lang: "en-US",
lang: "en-US"
};
"#;
files.push(("src/+config.ts".into(), CONFIG_SRC.into()));

const LAYOUT_SRC: &str = r#"import React from "react";
export let Layout: React.FC<React.PropsWithChildren> = ({ children }) => (
<div id="root">{children}</div>
);
"#;
files.push(("src/Layout.tsx".into(), LAYOUT_SRC.into()));

let head_src = format!(
r#"import React from "react";
import "./{css_path}";
Expand Down Expand Up @@ -775,7 +761,7 @@ export default () => {

files.push((
"index.html".into(),
Self::make_index_html(js_path, css_path).into(),
Self::make_index_html(js_path, &css_path).into(),
));

utils::create_dir(root.join("styles"))?;
Expand Down
13 changes: 13 additions & 0 deletions crates/depot/src/workspace/package.rs
Original file line number Diff line number Diff line change
Expand Up @@ -285,7 +285,20 @@ impl PackageInner {
["src", "tests"]
.into_iter()
.flat_map(|dir| self.iter_files(dir))
.chain(
[
"vite.config.ts",
"vite.config.mts",
"vitest.config.ts",
"vitest.config.mts",
]
.iter()
.map(PathBuf::from),
)
.filter_map(move |path| {
if !path.exists() {
return None;
}
let ext = path.extension()?;
source_extensions
.contains(ext.to_str().unwrap())
Expand Down

0 comments on commit f46196f

Please sign in to comment.