feat: support multiple staticDir entries (#3759)
## Summary - `staticDir` now accepts `string | string[]` in both the **Vite plugin** (`FreshViteConfig`) and the **Builder API** (`BuildOptions`) - When multiple directories are specified, they are searched in order and the first match wins - **Vite plugin**: first dir maps to Vite's native `publicDir`; extra dirs are served manually in the dev server and walked during production builds - **Builder API**: both `MemoryBuildCache` (dev) and `DiskBuildCache` (prod) iterate over all directories - Updated tailwind v3 plugin to use `config.root` instead of `path.dirname(config.staticDir)` - Docs updated: `static-files.md`, `vite.md`, `builder.md` Closes #3105 --------- Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 4.6
parent
c0a866d027
commit
990aeb03f3
@@ -22,7 +22,7 @@ jobs:
|
|||||||
|
|
||||||
test:
|
test:
|
||||||
runs-on: ${{ matrix.os }}
|
runs-on: ${{ matrix.os }}
|
||||||
timeout-minutes: 10
|
timeout-minutes: 15
|
||||||
|
|
||||||
strategy:
|
strategy:
|
||||||
fail-fast: false
|
fail-fast: false
|
||||||
|
|||||||
@@ -40,8 +40,10 @@ const builder = new Builder({
|
|||||||
// Where to write generated files when doing a production build.
|
// Where to write generated files when doing a production build.
|
||||||
// (default: `<root>/_fresh/`)
|
// (default: `<root>/_fresh/`)
|
||||||
outDir?: string;
|
outDir?: string;
|
||||||
// Path to static file directory. (Default: `<root>/static/`)
|
// Path to static file directory, or an array of directories.
|
||||||
staticDir?: string;
|
// When multiple directories are specified they are searched in order
|
||||||
|
// and the first match wins. (Default: `<root>/static/`)
|
||||||
|
staticDir?: string | string[];
|
||||||
// Path to island directory. (Default: `<root>/islands`)
|
// Path to island directory. (Default: `<root>/islands`)
|
||||||
islandDir?: string;
|
islandDir?: string;
|
||||||
// Path to routes directory. (Default: `<root>/routes`)
|
// Path to routes directory. (Default: `<root>/routes`)
|
||||||
@@ -93,8 +95,23 @@ builder.onTransformStaticFile({
|
|||||||
});
|
});
|
||||||
```
|
```
|
||||||
|
|
||||||
> [info]: Only static files in `static/` or the value you set `staticDir` to
|
> [info]: Only static files in `static/` or the directories you set `staticDir`
|
||||||
> will be processed. The builder won't process anything else.
|
> to will be processed. The builder won't process anything else.
|
||||||
|
|
||||||
|
### Multiple static directories
|
||||||
|
|
||||||
|
You can pass an array to `staticDir` to serve files from multiple directories.
|
||||||
|
When the same filename exists in more than one directory, the first directory in
|
||||||
|
the array takes precedence.
|
||||||
|
|
||||||
|
```ts dev.ts
|
||||||
|
const builder = new Builder({
|
||||||
|
staticDir: ["static", "generated"],
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
|
This is useful when you have a build step that generates assets into a separate
|
||||||
|
directory and you want to keep them apart from hand-authored static files.
|
||||||
|
|
||||||
## Testing
|
## Testing
|
||||||
|
|
||||||
|
|||||||
@@ -27,6 +27,10 @@ export default defineConfig({
|
|||||||
islandsDir: "./islands",
|
islandsDir: "./islands",
|
||||||
// Path to routes directory. Default: ./routes
|
// Path to routes directory. Default: ./routes
|
||||||
routeDir: "./routes",
|
routeDir: "./routes",
|
||||||
|
// Static file directory or directories. Default: "static"
|
||||||
|
// When multiple directories are given, they are searched in
|
||||||
|
// order and the first match wins.
|
||||||
|
staticDir: ["static", "generated"],
|
||||||
// Optional regex to ignore folders when crawling the routes and
|
// Optional regex to ignore folders when crawling the routes and
|
||||||
// island directory.
|
// island directory.
|
||||||
ignore: [/[\\/]+some-folder[\\/]+/],
|
ignore: [/[\\/]+some-folder[\\/]+/],
|
||||||
|
|||||||
@@ -47,6 +47,31 @@ pipeline, optimizes it, and adds a content hash to the filename for cache
|
|||||||
busting. Keeping these files outside `static/` ensures they're only included
|
busting. Keeping these files outside `static/` ensures they're only included
|
||||||
once in your build output.
|
once in your build output.
|
||||||
|
|
||||||
|
## Multiple static directories
|
||||||
|
|
||||||
|
You can serve files from more than one directory by passing an array to the
|
||||||
|
`staticDir` option. When the same filename exists in multiple directories, the
|
||||||
|
first directory in the array takes precedence.
|
||||||
|
|
||||||
|
```ts vite.config.ts
|
||||||
|
import { defineConfig } from "vite";
|
||||||
|
import { fresh } from "@fresh/plugin-vite";
|
||||||
|
|
||||||
|
export default defineConfig({
|
||||||
|
plugins: [
|
||||||
|
fresh({
|
||||||
|
staticDir: ["static", "generated"],
|
||||||
|
}),
|
||||||
|
],
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
|
This is useful when you have a build step that generates assets into a separate
|
||||||
|
directory and you want to keep them apart from hand-authored static files.
|
||||||
|
|
||||||
|
> [info]: If you're using the [Builder](/docs/advanced/builder) API instead of
|
||||||
|
> Vite, the same `staticDir` option accepts a string or an array of strings.
|
||||||
|
|
||||||
## Caching headers
|
## Caching headers
|
||||||
|
|
||||||
By default, Fresh adds caching headers for the `src` and `srcset` attributes on
|
By default, Fresh adds caching headers for the `src` and `srcset` attributes on
|
||||||
|
|||||||
@@ -57,13 +57,15 @@ export interface BuildOptions {
|
|||||||
*/
|
*/
|
||||||
outDir?: string;
|
outDir?: string;
|
||||||
/**
|
/**
|
||||||
* The directory to serve static files from.
|
* The directory (or directories) to serve static files from.
|
||||||
*
|
*
|
||||||
* This can be an absolute path, a file URL or a relative path.
|
* Each entry can be an absolute path, a file URL or a relative path.
|
||||||
* Relative paths are resolved against the `root` option.
|
* Relative paths are resolved against the `root` option.
|
||||||
|
* When multiple directories are specified, they are searched in order
|
||||||
|
* and the first match wins.
|
||||||
* @default "static"
|
* @default "static"
|
||||||
*/
|
*/
|
||||||
staticDir?: string;
|
staticDir?: string | string[];
|
||||||
/**
|
/**
|
||||||
* The directory which contains islands.
|
* The directory which contains islands.
|
||||||
*
|
*
|
||||||
@@ -103,11 +105,15 @@ export interface BuildOptions {
|
|||||||
/**
|
/**
|
||||||
* The final resolved Builder configuration.
|
* The final resolved Builder configuration.
|
||||||
*/
|
*/
|
||||||
export type ResolvedBuildConfig = Required<Omit<BuildOptions, "sourceMap">> & {
|
export type ResolvedBuildConfig =
|
||||||
mode: "development" | "production";
|
& Required<Omit<BuildOptions, "sourceMap" | "staticDir">>
|
||||||
buildId: string;
|
& {
|
||||||
sourceMap?: FreshBundleOptions["sourceMap"];
|
/** Always normalized to an array of absolute paths. */
|
||||||
};
|
staticDir: string[];
|
||||||
|
mode: "development" | "production";
|
||||||
|
buildId: string;
|
||||||
|
sourceMap?: FreshBundleOptions["sourceMap"];
|
||||||
|
};
|
||||||
|
|
||||||
// deno-lint-ignore no-explicit-any
|
// deno-lint-ignore no-explicit-any
|
||||||
export class Builder<State = any> {
|
export class Builder<State = any> {
|
||||||
@@ -122,7 +128,10 @@ export class Builder<State = any> {
|
|||||||
const root = parseDirPath(options?.root ?? ".", Deno.cwd());
|
const root = parseDirPath(options?.root ?? ".", Deno.cwd());
|
||||||
const serverEntry = parseDirPath(options?.serverEntry ?? "main.ts", root);
|
const serverEntry = parseDirPath(options?.serverEntry ?? "main.ts", root);
|
||||||
const outDir = parseDirPath(options?.outDir ?? "_fresh", root);
|
const outDir = parseDirPath(options?.outDir ?? "_fresh", root);
|
||||||
const staticDir = parseDirPath(options?.staticDir ?? "static", root);
|
const rawStaticDir = options?.staticDir ?? "static";
|
||||||
|
const staticDir =
|
||||||
|
(Array.isArray(rawStaticDir) ? rawStaticDir : [rawStaticDir])
|
||||||
|
.map((d) => parseDirPath(d, root));
|
||||||
const islandDir = parseDirPath(options?.islandDir ?? "islands", root);
|
const islandDir = parseDirPath(options?.islandDir ?? "islands", root);
|
||||||
const routeDir = parseDirPath(options?.routeDir ?? "routes", root);
|
const routeDir = parseDirPath(options?.routeDir ?? "routes", root);
|
||||||
|
|
||||||
|
|||||||
@@ -492,6 +492,106 @@ export const app = new App()
|
|||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
|
||||||
|
integrationTest("Builder - multiple staticDir in dev", async () => {
|
||||||
|
const root = path.join(import.meta.dirname!, "..", "..");
|
||||||
|
await using _tmp = await withTmpDir({ dir: root, prefix: "tmp_builder_" });
|
||||||
|
const tmp = _tmp.dir;
|
||||||
|
|
||||||
|
const app = new App()
|
||||||
|
.use(staticFiles())
|
||||||
|
.get("/", () => new Response("no"));
|
||||||
|
|
||||||
|
await writeFiles(tmp, {
|
||||||
|
"static_a/a.txt": "from a",
|
||||||
|
"static_a/shared.txt": "from a",
|
||||||
|
"static_b/b.txt": "from b",
|
||||||
|
"static_b/shared.txt": "from b",
|
||||||
|
});
|
||||||
|
|
||||||
|
const builder = new Builder({
|
||||||
|
root: tmp,
|
||||||
|
staticDir: ["static_a", "static_b"],
|
||||||
|
});
|
||||||
|
|
||||||
|
const controller = new AbortController();
|
||||||
|
const waiter = Promise.withResolvers<void>();
|
||||||
|
await builder.listen(() => Promise.resolve<App<unknown>>(app), {
|
||||||
|
signal: controller.signal,
|
||||||
|
async onListen(addr) {
|
||||||
|
try {
|
||||||
|
const base = `http://localhost:${addr.port}`;
|
||||||
|
|
||||||
|
// File only in first dir
|
||||||
|
let res = await fetch(`${base}/a.txt`);
|
||||||
|
expect(await res.text()).toEqual("from a");
|
||||||
|
|
||||||
|
// File only in second dir
|
||||||
|
res = await fetch(`${base}/b.txt`);
|
||||||
|
expect(await res.text()).toEqual("from b");
|
||||||
|
|
||||||
|
// File in both dirs — first dir wins
|
||||||
|
res = await fetch(`${base}/shared.txt`);
|
||||||
|
expect(await res.text()).toEqual("from a");
|
||||||
|
|
||||||
|
// File in neither dir
|
||||||
|
res = await fetch(`${base}/missing.txt`);
|
||||||
|
expect(res.status).toEqual(404);
|
||||||
|
|
||||||
|
controller.abort();
|
||||||
|
waiter.resolve();
|
||||||
|
} catch (err) {
|
||||||
|
waiter.reject(err);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
await waiter.promise;
|
||||||
|
});
|
||||||
|
|
||||||
|
integrationTest(
|
||||||
|
"Builder - multiple staticDir in prod",
|
||||||
|
async () => {
|
||||||
|
const root = path.join(import.meta.dirname!, "..", "..");
|
||||||
|
await using _tmp = await withTmpDir({
|
||||||
|
dir: root,
|
||||||
|
prefix: "tmp_builder_",
|
||||||
|
});
|
||||||
|
const tmp = _tmp.dir;
|
||||||
|
|
||||||
|
await writeFiles(tmp, {
|
||||||
|
"main.ts": `import { App, staticFiles } from "fresh";
|
||||||
|
export const app = new App()
|
||||||
|
.use(staticFiles());`,
|
||||||
|
"static_a/a.txt": "from a",
|
||||||
|
"static_a/shared.txt": "from a",
|
||||||
|
"static_b/b.txt": "from b",
|
||||||
|
"static_b/shared.txt": "from b",
|
||||||
|
});
|
||||||
|
|
||||||
|
await new Builder({
|
||||||
|
root: tmp,
|
||||||
|
staticDir: ["static_a", "static_b"],
|
||||||
|
}).build();
|
||||||
|
|
||||||
|
await withChildProcessServer(
|
||||||
|
{ cwd: tmp, args: ["serve", "-A", "--port=0", "_fresh/server.js"] },
|
||||||
|
async (address) => {
|
||||||
|
// File only in first dir
|
||||||
|
let res = await fetch(`${address}/a.txt`);
|
||||||
|
expect(await res.text()).toEqual("from a");
|
||||||
|
|
||||||
|
// File only in second dir
|
||||||
|
res = await fetch(`${address}/b.txt`);
|
||||||
|
expect(await res.text()).toEqual("from b");
|
||||||
|
|
||||||
|
// File in both dirs — first dir wins
|
||||||
|
res = await fetch(`${address}/shared.txt`);
|
||||||
|
expect(await res.text()).toEqual("from a");
|
||||||
|
},
|
||||||
|
);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
integrationTest("Builder - custom server entry", async () => {
|
integrationTest("Builder - custom server entry", async () => {
|
||||||
const root = path.join(import.meta.dirname!, "..", "..");
|
const root = path.join(import.meta.dirname!, "..", "..");
|
||||||
await using _tmp = await withTmpDir({ dir: root, prefix: "tmp_builder_" });
|
await using _tmp = await withTmpDir({ dir: root, prefix: "tmp_builder_" });
|
||||||
|
|||||||
@@ -130,50 +130,53 @@ export class MemoryBuildCache<State> implements DevBuildCache<State> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
let entry = pathname.startsWith("/") ? pathname.slice(1) : pathname;
|
const stripped = pathname.startsWith("/") ? pathname.slice(1) : pathname;
|
||||||
entry = path.join(this.#config.staticDir, entry);
|
|
||||||
const relative = path.relative(this.#config.staticDir, entry);
|
for (const staticDir of this.#config.staticDir) {
|
||||||
if (relative.startsWith("..")) {
|
const entry = path.join(staticDir, stripped);
|
||||||
throw new Error(
|
const relative = path.relative(staticDir, entry);
|
||||||
`Processed file resolved outside of static dir ${entry}`,
|
if (relative.startsWith("..")) {
|
||||||
|
throw new Error(
|
||||||
|
`Processed file resolved outside of static dir ${entry}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Might be a file that we still need to process
|
||||||
|
const transformed = await this.#transformer.process(
|
||||||
|
entry,
|
||||||
|
"development",
|
||||||
|
this.#config.target,
|
||||||
);
|
);
|
||||||
}
|
|
||||||
|
|
||||||
// Might be a file that we still need to process
|
if (transformed !== null) {
|
||||||
const transformed = await this.#transformer.process(
|
for (let i = 0; i < transformed.length; i++) {
|
||||||
entry,
|
const file = transformed[i];
|
||||||
"development",
|
const rel = path.relative(staticDir, file.path);
|
||||||
this.#config.target,
|
if (rel.startsWith("..")) {
|
||||||
);
|
throw new Error(
|
||||||
|
`Processed file resolved outside of static dir ${file.path}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
const filePathname = new URL(rel, "http://localhost").pathname;
|
||||||
|
|
||||||
if (transformed !== null) {
|
this.addProcessedFile(filePathname, file.content, null);
|
||||||
for (let i = 0; i < transformed.length; i++) {
|
|
||||||
const file = transformed[i];
|
|
||||||
const relative = path.relative(this.#config.staticDir, file.path);
|
|
||||||
if (relative.startsWith("..")) {
|
|
||||||
throw new Error(
|
|
||||||
`Processed file resolved outside of static dir ${file.path}`,
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
const pathname = new URL(relative, "http://localhost").pathname;
|
if (this.#processedFiles.has(pathname)) {
|
||||||
|
|
||||||
this.addProcessedFile(pathname, file.content, null);
|
|
||||||
}
|
|
||||||
if (this.#processedFiles.has(pathname)) {
|
|
||||||
return this.readFile(pathname);
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
try {
|
|
||||||
const filePath = path.join(this.#config.staticDir, pathname);
|
|
||||||
const relative = path.relative(this.#config.staticDir, filePath);
|
|
||||||
if (!relative.startsWith("..") && (await Deno.stat(filePath)).isFile) {
|
|
||||||
const pathname = new URL(relative, "http://localhost").pathname;
|
|
||||||
this.addUnprocessedFile(pathname, this.#config.staticDir);
|
|
||||||
return this.readFile(pathname);
|
return this.readFile(pathname);
|
||||||
}
|
}
|
||||||
} catch (err) {
|
} else {
|
||||||
if (!(err instanceof Deno.errors.NotFound)) {
|
try {
|
||||||
throw err;
|
const filePath = path.join(staticDir, pathname);
|
||||||
|
const rel = path.relative(staticDir, filePath);
|
||||||
|
if (!rel.startsWith("..") && (await Deno.stat(filePath)).isFile) {
|
||||||
|
const filePathname = new URL(rel, "http://localhost").pathname;
|
||||||
|
this.addUnprocessedFile(filePathname, staticDir);
|
||||||
|
return this.readFile(filePathname);
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
if (!(err instanceof Deno.errors.NotFound)) {
|
||||||
|
throw err;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -303,9 +306,13 @@ export class DiskBuildCache<State> implements DevBuildCache<State> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async flush(): Promise<void> {
|
async flush(): Promise<void> {
|
||||||
const { staticDir, outDir, target, root } = this.#config;
|
const { staticDir: staticDirs, outDir, target, root } = this.#config;
|
||||||
|
|
||||||
|
const seen = new Set<string>();
|
||||||
|
|
||||||
|
for (const staticDir of staticDirs) {
|
||||||
|
if (!(await fsAdapter.isDirectory(staticDir))) continue;
|
||||||
|
|
||||||
if (await fsAdapter.isDirectory(staticDir)) {
|
|
||||||
const entries = fsAdapter.walk(staticDir, {
|
const entries = fsAdapter.walk(staticDir, {
|
||||||
includeDirs: false,
|
includeDirs: false,
|
||||||
includeFiles: true,
|
includeFiles: true,
|
||||||
@@ -332,12 +339,18 @@ export class DiskBuildCache<State> implements DevBuildCache<State> {
|
|||||||
const file = result[i];
|
const file = result[i];
|
||||||
assertInDir(file.path, staticDir);
|
assertInDir(file.path, staticDir);
|
||||||
const pathname = `/${path.relative(staticDir, file.path)}`;
|
const pathname = `/${path.relative(staticDir, file.path)}`;
|
||||||
await this.addProcessedFile(pathname, file.content, null);
|
if (!seen.has(pathname)) {
|
||||||
|
seen.add(pathname);
|
||||||
|
await this.addProcessedFile(pathname, file.content, null);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
const relative = path.relative(staticDir, entry.path);
|
const relative = path.relative(staticDir, entry.path);
|
||||||
const pathname = `/${relative}`;
|
const pathname = `/${relative}`;
|
||||||
this.addUnprocessedFile(pathname, staticDir);
|
if (!seen.has(pathname)) {
|
||||||
|
seen.add(pathname);
|
||||||
|
this.addUnprocessedFile(pathname, staticDir);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -22,7 +22,7 @@ Deno.test({
|
|||||||
islandDir: "",
|
islandDir: "",
|
||||||
outDir: "",
|
outDir: "",
|
||||||
routeDir: "",
|
routeDir: "",
|
||||||
staticDir: "",
|
staticDir: [""],
|
||||||
target: "latest",
|
target: "latest",
|
||||||
};
|
};
|
||||||
const fileTransformer = new FileTransformer(createFakeFs({}), tmp);
|
const fileTransformer = new FileTransformer(createFakeFs({}), tmp);
|
||||||
|
|||||||
@@ -106,7 +106,7 @@ async function initTailwind(
|
|||||||
config: ResolvedBuildConfig,
|
config: ResolvedBuildConfig,
|
||||||
options: TailwindPluginOptions,
|
options: TailwindPluginOptions,
|
||||||
): Promise<postcss.Processor> {
|
): Promise<postcss.Processor> {
|
||||||
const root = path.dirname(config.staticDir);
|
const root = config.root;
|
||||||
|
|
||||||
const configPath = await findTailwindConfigFile(root);
|
const configPath = await findTailwindConfigFile(root);
|
||||||
const url = path.toFileUrl(configPath).href;
|
const url = path.toFileUrl(configPath).href;
|
||||||
|
|||||||
@@ -55,11 +55,13 @@ export type {
|
|||||||
* ```
|
* ```
|
||||||
*/
|
*/
|
||||||
export function fresh(config?: FreshViteConfig): Plugin[] {
|
export function fresh(config?: FreshViteConfig): Plugin[] {
|
||||||
|
const rawStaticDir = config?.staticDir ?? "static";
|
||||||
const fConfig: ResolvedFreshViteConfig = {
|
const fConfig: ResolvedFreshViteConfig = {
|
||||||
serverEntry: config?.serverEntry ?? "main.ts",
|
serverEntry: config?.serverEntry ?? "main.ts",
|
||||||
clientEntry: config?.clientEntry ?? "client.ts",
|
clientEntry: config?.clientEntry ?? "client.ts",
|
||||||
islandsDir: config?.islandsDir ?? "islands",
|
islandsDir: config?.islandsDir ?? "islands",
|
||||||
routeDir: config?.routeDir ?? "routes",
|
routeDir: config?.routeDir ?? "routes",
|
||||||
|
staticDir: Array.isArray(rawStaticDir) ? rawStaticDir : [rawStaticDir],
|
||||||
ignore: config?.ignore ?? [TEST_FILE_PATTERN],
|
ignore: config?.ignore ?? [TEST_FILE_PATTERN],
|
||||||
islandSpecifiers: new Map(),
|
islandSpecifiers: new Map(),
|
||||||
namer: new UniqueNamer(),
|
namer: new UniqueNamer(),
|
||||||
@@ -111,7 +113,7 @@ export function fresh(config?: FreshViteConfig): Plugin[] {
|
|||||||
noDiscovery: true,
|
noDiscovery: true,
|
||||||
},
|
},
|
||||||
|
|
||||||
publicDir: pathWithRoot("static", config.root),
|
publicDir: pathWithRoot(fConfig.staticDir[0], config.root),
|
||||||
|
|
||||||
builder: {
|
builder: {
|
||||||
async buildApp(builder) {
|
async buildApp(builder) {
|
||||||
@@ -208,6 +210,9 @@ export function fresh(config?: FreshViteConfig): Plugin[] {
|
|||||||
|
|
||||||
fConfig.islandsDir = pathWithRoot(fConfig.islandsDir, vConfig.root);
|
fConfig.islandsDir = pathWithRoot(fConfig.islandsDir, vConfig.root);
|
||||||
fConfig.routeDir = pathWithRoot(fConfig.routeDir, vConfig.root);
|
fConfig.routeDir = pathWithRoot(fConfig.routeDir, vConfig.root);
|
||||||
|
fConfig.staticDir = fConfig.staticDir.map((d) =>
|
||||||
|
pathWithRoot(d, vConfig.root)
|
||||||
|
);
|
||||||
|
|
||||||
config?.islandSpecifiers?.map((spec) => {
|
config?.islandSpecifiers?.map((spec) => {
|
||||||
const specName = specToName(spec);
|
const specName = specToName(spec);
|
||||||
@@ -233,7 +238,7 @@ export function fresh(config?: FreshViteConfig): Plugin[] {
|
|||||||
clientEntryPlugin(fConfig),
|
clientEntryPlugin(fConfig),
|
||||||
...clientSnapshot(fConfig),
|
...clientSnapshot(fConfig),
|
||||||
buildIdPlugin(),
|
buildIdPlugin(),
|
||||||
...devServer(),
|
...devServer(fConfig),
|
||||||
prefresh({
|
prefresh({
|
||||||
include: [/\.[cm]?[tj]sx?$/],
|
include: [/\.[cm]?[tj]sx?$/],
|
||||||
exclude: [/node_modules/, /[\\/]+deno[\\/]+npm[\\/]+/],
|
exclude: [/node_modules/, /[\\/]+deno[\\/]+npm[\\/]+/],
|
||||||
|
|||||||
@@ -1,10 +1,16 @@
|
|||||||
import type { DevEnvironment, Plugin } from "vite";
|
import type { DevEnvironment, Plugin } from "vite";
|
||||||
import * as path from "@std/path";
|
import * as path from "@std/path";
|
||||||
|
import { contentType as getStdContentType } from "@std/media-types/content-type";
|
||||||
import { ASSET_CACHE_BUST_KEY } from "fresh/internal";
|
import { ASSET_CACHE_BUST_KEY } from "fresh/internal";
|
||||||
import { createRequest, sendResponse } from "@remix-run/node-fetch-server";
|
import { createRequest, sendResponse } from "@remix-run/node-fetch-server";
|
||||||
import { hashCode } from "../shared.ts";
|
import { hashCode } from "../shared.ts";
|
||||||
|
import type { ResolvedFreshViteConfig } from "../utils.ts";
|
||||||
|
|
||||||
export function devServer(): Plugin[] {
|
function getContentType(ext: string): string {
|
||||||
|
return getStdContentType(ext) ?? "application/octet-stream";
|
||||||
|
}
|
||||||
|
|
||||||
|
export function devServer(freshConfig: ResolvedFreshViteConfig): Plugin[] {
|
||||||
let publicDir = "";
|
let publicDir = "";
|
||||||
return [
|
return [
|
||||||
{
|
{
|
||||||
@@ -53,30 +59,55 @@ export function devServer(): Plugin[] {
|
|||||||
|
|
||||||
const decodedPathname = decodeURIComponent(url.pathname.slice(1));
|
const decodedPathname = decodeURIComponent(url.pathname.slice(1));
|
||||||
|
|
||||||
// Check if it's a static file first
|
// Check if it's a static file first.
|
||||||
const staticFilePath = path.join(publicDir, decodedPathname);
|
// Vite handles publicDir (the first static dir) natively,
|
||||||
try {
|
// but we also need to check extra static dirs.
|
||||||
const stat = await Deno.stat(staticFilePath);
|
const extraStaticDirs = freshConfig.staticDir.slice(1);
|
||||||
if (stat.isFile) {
|
const allStaticDirs = [publicDir, ...extraStaticDirs];
|
||||||
return next();
|
let handledStatic = false;
|
||||||
|
for (const dir of allStaticDirs) {
|
||||||
|
const staticFilePath = path.join(dir, decodedPathname);
|
||||||
|
try {
|
||||||
|
const stat = await Deno.stat(staticFilePath);
|
||||||
|
if (stat.isFile) {
|
||||||
|
if (dir === publicDir) {
|
||||||
|
// Vite serves publicDir files natively
|
||||||
|
return next();
|
||||||
|
}
|
||||||
|
// Serve files from extra dirs manually
|
||||||
|
const file = await Deno.open(staticFilePath, { read: true });
|
||||||
|
const { ext } = path.parse(staticFilePath);
|
||||||
|
const contentType = getContentType(ext);
|
||||||
|
nodeRes.setHeader("Content-Type", contentType);
|
||||||
|
// deno-lint-ignore no-explicit-any
|
||||||
|
for await (const chunk of file.readable as any) {
|
||||||
|
nodeRes.write(chunk);
|
||||||
|
}
|
||||||
|
nodeRes.end();
|
||||||
|
handledStatic = true;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
// Ignore
|
||||||
}
|
}
|
||||||
} catch {
|
|
||||||
// Ignore
|
|
||||||
}
|
}
|
||||||
|
if (handledStatic) return;
|
||||||
|
|
||||||
// Check if it's a static/index.html file
|
// Check if it's a static/index.html file
|
||||||
const staticFilePathIndex = path.join(
|
for (const dir of allStaticDirs) {
|
||||||
publicDir,
|
const staticFilePathIndex = path.join(
|
||||||
decodedPathname,
|
dir,
|
||||||
"index.html",
|
decodedPathname,
|
||||||
);
|
"index.html",
|
||||||
try {
|
);
|
||||||
const content = await Deno.readTextFile(staticFilePathIndex);
|
try {
|
||||||
nodeRes.setHeader("Content-Type", "text/html; charset=utf-8");
|
const content = await Deno.readTextFile(staticFilePathIndex);
|
||||||
nodeRes.end(content);
|
nodeRes.setHeader("Content-Type", "text/html; charset=utf-8");
|
||||||
return;
|
nodeRes.end(content);
|
||||||
} catch {
|
return;
|
||||||
// Ignore
|
} catch {
|
||||||
|
// Ignore
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
|
|||||||
@@ -32,7 +32,6 @@ export function serverSnapshot(options: ResolvedFreshViteConfig): Plugin[] {
|
|||||||
let clientOutDir = "";
|
let clientOutDir = "";
|
||||||
let serverOutDir = "";
|
let serverOutDir = "";
|
||||||
let root = "";
|
let root = "";
|
||||||
let publicDir = "";
|
|
||||||
|
|
||||||
const islands = new Map<string, { name: string; chunk: string | null }>();
|
const islands = new Map<string, { name: string; chunk: string | null }>();
|
||||||
const islandsByFile = new Set<string>();
|
const islandsByFile = new Set<string>();
|
||||||
@@ -56,7 +55,6 @@ export function serverSnapshot(options: ResolvedFreshViteConfig): Plugin[] {
|
|||||||
configResolved(config) {
|
configResolved(config) {
|
||||||
root = config.root;
|
root = config.root;
|
||||||
|
|
||||||
publicDir = pathWithRoot(config.publicDir, config.root);
|
|
||||||
clientOutDir = pathWithRoot(
|
clientOutDir = pathWithRoot(
|
||||||
config.environments.client.build.outDir,
|
config.environments.client.build.outDir,
|
||||||
config.root,
|
config.root,
|
||||||
@@ -274,9 +272,14 @@ export function serverSnapshot(options: ResolvedFreshViteConfig): Plugin[] {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (await fsAdapter.isDirectory(publicDir)) {
|
// Walk all static directories. First directory wins for
|
||||||
|
// duplicate pathnames.
|
||||||
|
const seenStaticPaths = new Set<string>();
|
||||||
|
for (const dir of options.staticDir) {
|
||||||
|
if (!(await fsAdapter.isDirectory(dir))) continue;
|
||||||
|
|
||||||
const entries = await fsAdapter.walk(
|
const entries = await fsAdapter.walk(
|
||||||
publicDir,
|
dir,
|
||||||
{
|
{
|
||||||
followSymlinks: false,
|
followSymlinks: false,
|
||||||
includeDirs: false,
|
includeDirs: false,
|
||||||
@@ -286,11 +289,16 @@ export function serverSnapshot(options: ResolvedFreshViteConfig): Plugin[] {
|
|||||||
);
|
);
|
||||||
|
|
||||||
for await (const entry of entries) {
|
for await (const entry of entries) {
|
||||||
const relative = path.relative(publicDir, entry.path);
|
const relative = path.relative(dir, entry.path);
|
||||||
|
if (seenStaticPaths.has(relative)) continue;
|
||||||
|
seenStaticPaths.add(relative);
|
||||||
|
|
||||||
const filePath = path.join(clientOutDir, relative);
|
const filePath = path.join(clientOutDir, relative);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
await Deno.mkdir(path.dirname(filePath), { recursive: true });
|
await Deno.mkdir(path.dirname(filePath), {
|
||||||
|
recursive: true,
|
||||||
|
});
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
if (!(err instanceof Deno.errors.AlreadyExists)) {
|
if (!(err instanceof Deno.errors.AlreadyExists)) {
|
||||||
throw err;
|
throw err;
|
||||||
@@ -306,15 +314,18 @@ export function serverSnapshot(options: ResolvedFreshViteConfig): Plugin[] {
|
|||||||
|
|
||||||
if (path.basename(relative) === "index.html") {
|
if (path.basename(relative) === "index.html") {
|
||||||
const htmlRelative = path.relative(
|
const htmlRelative = path.relative(
|
||||||
publicDir,
|
dir,
|
||||||
path.dirname(entry.path),
|
path.dirname(entry.path),
|
||||||
);
|
);
|
||||||
|
|
||||||
staticFiles.push({
|
if (!seenStaticPaths.has(htmlRelative)) {
|
||||||
filePath,
|
seenStaticPaths.add(htmlRelative);
|
||||||
hash: null,
|
staticFiles.push({
|
||||||
pathname: htmlRelative,
|
filePath,
|
||||||
});
|
hash: null,
|
||||||
|
pathname: htmlRelative,
|
||||||
|
});
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -45,6 +45,12 @@ export interface FreshViteConfig {
|
|||||||
islandsDir?: string;
|
islandsDir?: string;
|
||||||
/** Path to routes directory. Default: `./routes` */
|
/** Path to routes directory. Default: `./routes` */
|
||||||
routeDir?: string;
|
routeDir?: string;
|
||||||
|
/**
|
||||||
|
* The directory (or directories) to serve static files from.
|
||||||
|
* When multiple directories are specified, they are searched in order
|
||||||
|
* and the first match wins. Default: `"static"`
|
||||||
|
*/
|
||||||
|
staticDir?: string | string[];
|
||||||
/**
|
/**
|
||||||
* Ignore file paths matching any of the provided regexes when
|
* Ignore file paths matching any of the provided regexes when
|
||||||
* crawling the islands and routes directories.
|
* crawling the islands and routes directories.
|
||||||
@@ -67,6 +73,10 @@ export interface FreshViteConfig {
|
|||||||
|
|
||||||
export type ResolvedFreshViteConfig =
|
export type ResolvedFreshViteConfig =
|
||||||
& Required<
|
& Required<
|
||||||
Omit<FreshViteConfig, "islandSpecifiers">
|
Omit<FreshViteConfig, "islandSpecifiers" | "staticDir">
|
||||||
>
|
>
|
||||||
& { islandSpecifiers: Map<string, string>; namer: UniqueNamer };
|
& {
|
||||||
|
staticDir: string[];
|
||||||
|
islandSpecifiers: Map<string, string>;
|
||||||
|
namer: UniqueNamer;
|
||||||
|
};
|
||||||
|
|||||||
Reference in New Issue
Block a user