Skip to content

Commit

Permalink
feat: optimize deps enhancements
Browse files Browse the repository at this point in the history
  • Loading branch information
lazarv committed Sep 18, 2024
1 parent f6658b3 commit df130b8
Show file tree
Hide file tree
Showing 10 changed files with 171 additions and 73 deletions.
9 changes: 0 additions & 9 deletions examples/mantine/react-server.config.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,6 @@ export default {
optimizeDeps: {
exclude: ["@mantine/core"],
},
resolve: {
alias: [
{
find: "highlight.js",
replacement: "highlight.js",
},
],
external: ["dayjs"],
},
build: {
chunkSizeWarningLimit: 1000,
rollupOptions: {
Expand Down
2 changes: 0 additions & 2 deletions examples/mantine/src/components/AppLayout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -40,11 +40,9 @@ export function AppLayout({
</Link>
</Group>
</AppShell.Header>

<AppShell.Navbar p="md">
<MainNavigation serverPathname={serverPathname} />
</AppShell.Navbar>

<AppShell.Main>{children}</AppShell.Main>
</AppShell>
);
Expand Down
4 changes: 3 additions & 1 deletion examples/mantine/src/components/AppLogo.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
const SVGComponent = (props) => (
import type { SVGProps } from "react";

const SVGComponent = (props: SVGProps<SVGSVGElement>) => (
<svg
width="128"
height="128"
Expand Down
33 changes: 24 additions & 9 deletions examples/mantine/src/components/MyDates.tsx
Original file line number Diff line number Diff line change
@@ -1,20 +1,35 @@
"use client";

import "dayjs/locale/de";

import { useState } from "react";

import { Select } from "@mantine/core";
import { DateInput } from "@mantine/dates";
import dayjs from "dayjs";
import de from "dayjs/locale/de";

dayjs.locale(de);

export default function MyDates() {
const [value, setValue] = useState<Date | null>(null);
const [locale, setLocale] = useState("en");

return (
<DateInput
//locale="de"
value={value}
onChange={setValue}
label="Date input"
placeholder="Date input"
/>
<>
<Select
data={[
{ value: "en", label: "English" },
{ value: "de", label: "German" },
]}
value={locale}
onChange={(value) => setLocale(value ?? "en")}
/>
<DateInput
locale={locale}
value={value}
onChange={setValue}
label="Date input"
placeholder="Date input"
/>
</>
);
}
5 changes: 0 additions & 5 deletions examples/todo/react-server.config.json

This file was deleted.

91 changes: 63 additions & 28 deletions packages/react-server/lib/build/server.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,13 @@ import rollupUseServer from "../plugins/use-server.mjs";
import * as sys from "../sys.mjs";
import { makeResolveAlias } from "../utils/config.mjs";
import merge from "../utils/merge.mjs";
import { bareImportRE } from "../utils/module.mjs";
import {
filterOutVitePluginReact,
userOrBuiltInVitePluginReact,
} from "../utils/plugins.mjs";
import banner from "./banner.mjs";
import customLogger from "./custom-logger.mjs";
import { bareImportRE, findNearestPackageData } from "../utils/module.mjs";

const __require = createRequire(import.meta.url);
const cwd = sys.cwd();
Expand All @@ -38,6 +38,65 @@ export default async function serverBuild(root, options) {
...userOrBuiltInVitePluginReact(config.plugins),
...filterOutVitePluginReact(config.plugins),
];

const external = (id, parentId, isResolved) => {
const external = [
/manifest\.json/,
/^bun:/,
/^node:/,
"react",
"react/jsx-runtime",
"react-dom",
"react-dom/client",
"react-dom/server.edge",
"react-server-dom-webpack/client.browser",
"react-server-dom-webpack/client.edge",
"react-server-dom-webpack/server.edge",
"react-is",
"picocolors",
...(Array.isArray(config.build?.rollupOptions?.external)
? config.build?.rollupOptions?.external
: []),
...(config.external ?? []),
];
for (const mod of external) {
if (
(typeof mod === "string" && id === mod) ||
(mod instanceof RegExp && mod.test(id))
) {
return true;
}
}
if (typeof config.build?.rollupOptions?.external === "function") {
const isExternal = config.build?.rollupOptions?.external(
id,
parentId,
isResolved
);
if (isExternal) {
return true;
}
}
return false;
};
const rscExternal = (id) => {
if (bareImportRE.test(id)) {
try {
const mod = __require.resolve(id, { paths: [cwd] });
const pkg = findNearestPackageData(mod);
if (
/[cm]?js$/.test(mod) &&
!(pkg?.type === "module" || pkg?.module || pkg?.exports)
) {
return true;
}
} catch {
// ignore
}
}
return false;
};

const buildConfig = {
root: cwd,
configFile: false,
Expand Down Expand Up @@ -121,33 +180,8 @@ export default async function serverBuild(root, options) {
}
),
},
external(id) {
const external = [
/manifest\.json/,
/^bun:/,
/^node:/,
"react",
"react/jsx-runtime",
"react-dom",
"react-dom/client",
"react-dom/server.edge",
"react-server-dom-webpack/client.browser",
"react-server-dom-webpack/client.edge",
"react-server-dom-webpack/server.edge",
"react-is",
"picocolors",
...(config.build?.rollupOptions?.external ?? []),
...(config.external ?? []),
];
for (const mod of external) {
if (
(typeof mod === "string" && id === mod) ||
(mod instanceof RegExp && mod.test(id))
) {
return true;
}
}
return false;
external(id, parentId, isResolved) {
return external(id, parentId, isResolved) || rscExternal(id);
},
plugins: [
resolveWorkspace(),
Expand Down Expand Up @@ -225,6 +259,7 @@ export default async function serverBuild(root, options) {
},
{}
),
external,
plugins: [
resolveWorkspace(),
replace({
Expand Down
1 change: 1 addition & 0 deletions packages/react-server/lib/dev/create-server.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,7 @@ export default async function createServer(root, options) {
clearScreen: options.clearScreen,
configFile: false,
optimizeDeps: {
holdUntilCrawlEnd: true,
...config.optimizeDeps,
force: options.force || config.optimizeDeps?.force,
include: [
Expand Down
17 changes: 16 additions & 1 deletion packages/react-server/lib/handlers/error.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -130,16 +130,31 @@ export default async function errorHandler(err) {
statusText: "Internal Server Error",
};

const error = await prepareError(err);

const viteDevServer = getContext(SERVER_CONTEXT);
if (viteDevServer) {
try {
viteDevServer.environments.client.moduleGraph.invalidateAll();
viteDevServer.environments.ssr.moduleGraph.invalidateAll();
viteDevServer.environments.rsc.moduleGraph.invalidateAll();
} catch (e) {
// ignore
}
}

return new Response(
`<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Error</title>
<script type="module" src="${`${server.config.base || "/"}/@vite/client`.replace(/\/+/g, "/")}"></script>
<script type="module" src="${`${server.config.base || "/"}/@hmr`.replace(/\/+/g, "/")}"></script>
<script type="module">
import { ErrorOverlay } from "${`${server.config.base || "/"}/@vite/client`.replace(/\/+/g, "/")}";
document.body.appendChild(new ErrorOverlay(${JSON.stringify(
await prepareError(err)
error
).replace(/</g, "\\u003c")}))
</script>
</head>
Expand Down
43 changes: 40 additions & 3 deletions packages/react-server/lib/plugins/optimize-deps.mjs
Original file line number Diff line number Diff line change
@@ -1,6 +1,13 @@
import { readFile } from "node:fs/promises";

import { moduleAliases } from "../loader/module-alias.mjs";
import { applyAlias } from "../loader/utils.mjs";
import { bareImportRE, isModule, tryStat } from "../utils/module.mjs";
import {
bareImportRE,
isModule,
isRootModule,
tryStat,
} from "../utils/module.mjs";

const alias = moduleAliases();

Expand All @@ -17,14 +24,42 @@ export default function optimizeDeps() {
);
const path = resolved?.id?.split("?")[0];
if (
(this.environment.name === "rsc" ||
this.environment.name === "ssr") &&
/\.[cm]?js$/.test(path) &&
(bareImportRE.test(specifier) ||
(specifier[0] !== "." && specifier[0] !== "/")) &&
applyAlias(alias, specifier) === specifier &&
!isModule(path) &&
tryStat(path)?.isFile()
) {
try {
const content = await readFile(path, "utf-8");
const ast = this.parse(content);
const hasImportExport = ast.body.some(
(node) =>
node.type === "ImportDeclaration" ||
node.type === "ExportNamedDeclaration" ||
node.type === "ExportDefaultDeclaration" ||
node.type === "ExportAllDeclaration"
);
if (hasImportExport) {
return resolved;
}
} catch (e) {
console.log("error", path, e);
// ignore
}
return { externalize: specifier };
} else if (
this.environment.name === "client" &&
!this.environment.depsOptimizer?.isOptimizedDepFile(specifier) &&
path &&
/\.[cm]?js$/.test(path) &&
(bareImportRE.test(specifier) ||
(specifier[0] !== "." && specifier[0] !== "/")) &&
applyAlias(alias, specifier) === specifier &&
!isModule(path) &&
!isRootModule(path) &&
tryStat(path)?.isFile()
) {
try {
Expand All @@ -33,6 +68,9 @@ export default function optimizeDeps() {
specifier,
path
);
this.environment.depsOptimizer.metadata.discovered[specifier] = {
...optimizedInfo,
};
return {
id: this.environment.depsOptimizer.getOptimizedDepId(
optimizedInfo
Expand All @@ -45,7 +83,6 @@ export default function optimizeDeps() {
return resolved || { externalize: specifier };
} catch {
return { externalize: specifier };
// ignore
}
},
};
Expand Down
Loading

0 comments on commit df130b8

Please sign in to comment.