forked from denoland/fresh
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmod.ts
More file actions
261 lines (238 loc) · 7.8 KB
/
mod.ts
File metadata and controls
261 lines (238 loc) · 7.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
import type { Plugin } from "vite";
import {
type FreshViteConfig,
pathWithRoot,
type ResolvedFreshViteConfig,
} from "./utils.ts";
import { deno } from "./plugins/deno.ts";
import prefresh from "@prefresh/vite";
import { serverEntryPlugin } from "./plugins/server_entry.ts";
import { clientEntryPlugin } from "./plugins/client_entry.ts";
import { devServer } from "./plugins/dev_server.ts";
import { buildIdPlugin } from "./plugins/build_id.ts";
import { clientSnapshot } from "./plugins/client_snapshot.ts";
import { serverSnapshot } from "./plugins/server_snapshot.ts";
import { patches } from "./plugins/patches.ts";
import process from "node:process";
import {
specToName,
TEST_FILE_PATTERN,
UniqueNamer,
UPDATE_INTERVAL,
updateCheck,
} from "@fresh/core/internal-dev";
import { checkImports } from "./plugins/verify_imports.ts";
import { isBuiltin } from "node:module";
import { load as stdLoadEnv } from "@std/dotenv";
import path from "node:path";
export type { FreshViteConfig };
export type {
ImportCheck,
ImportCheckDiagnostic,
} from "./plugins/verify_imports.ts";
/**
* Fresh framework support for Vite.
*
* This plugin uses the Environments feature of Vite to build
* both the server and client code for Fresh applications.
*
* @param config Fresh config options
* @returns Vite plugin with Fresh support
*
* @example Basic usage
* ```ts vite.config.ts
* import { defineConfig } from "vite";
* import { fresh } from "@fresh/plugin-vite";
*
* export default defineConfig({
* plugins: [
* fresh({ serverEntry: "server.ts" })
* ],
* });
* ```
*/
export function fresh(config?: FreshViteConfig): Plugin[] {
const fConfig: ResolvedFreshViteConfig = {
serverEntry: config?.serverEntry ?? "main.ts",
clientEntry: config?.clientEntry ?? "client.ts",
islandsDir: config?.islandsDir ?? "islands",
routeDir: config?.routeDir ?? "routes",
ignore: config?.ignore ?? [TEST_FILE_PATTERN],
islandSpecifiers: new Map(),
namer: new UniqueNamer(),
checkImports: config?.checkImports ?? [],
};
fConfig.checkImports.push((id, env) => {
if (env === "client") {
if (isBuiltin(id)) {
return {
type: "error",
message: "Node built-in modules cannot be imported in the browser.",
description:
"This is an error in your application code or in one of its dependencies.",
};
}
}
});
let isDev = false;
const plugins: Plugin[] = [
{
name: "fresh",
sharedDuringBuild: true,
config(config, env) {
isDev = env.command === "serve";
return {
esbuild: {
jsx: "automatic",
jsxImportSource: "preact",
jsxDev: env.command === "serve",
},
resolve: {
alias: {
"react-dom/test-utils": "preact/test-utils",
"react-dom": "preact/compat",
react: "preact/compat",
},
// Disallow externals, because it leads to duplicate
// modules with `preact` vs `npm:preact@*` in the server
// environment.
noExternal: true,
},
optimizeDeps: {
// Optimize deps somehow leads to duplicate modules or them
// being placed in the wrong chunks...
noDiscovery: true,
},
publicDir: pathWithRoot("static", config.root),
builder: {
async buildApp(builder) {
// Build client env first
const clientEnv = builder.environments.client;
if (clientEnv !== undefined) {
await builder.build(clientEnv);
}
await Promise.all(
Object.values(builder.environments).filter((env) =>
env !== clientEnv
).map((env) => builder.build(env)),
);
},
},
environments: {
client: {
build: {
copyPublicDir: false,
manifest: true,
outDir: config.environments?.client?.build?.outDir ??
(config.build?.outDir
? config.build.outDir + "/client"
: null) ??
"_fresh/client",
rollupOptions: {
preserveEntrySignatures: "strict",
input: {
"client-entry": "fresh:client-entry",
},
},
},
},
ssr: {
build: {
manifest: true,
emitAssets: true,
copyPublicDir: false,
outDir: config.environments?.ssr?.build?.outDir ??
(config.build?.outDir
? config.build.outDir + "/server"
: null) ??
"_fresh/server",
rollupOptions: {
onwarn(warning, handler) {
// Ignore "use client"; warnings
if (warning.code === "MODULE_LEVEL_DIRECTIVE") {
return;
}
// Ignore optional export errors
if (
warning.code === "MISSING_EXPORT" &&
warning.id?.startsWith("\0fresh-route::")
) {
return;
}
// Ignore commonjs optional exports
if (
warning.code === "MISSING_EXPORT" &&
warning.message.includes("__require")
) {
return;
}
// Ignore this warnings
if (warning.code === "THIS_IS_UNDEFINED") {
return;
}
// Ignore falsy source map errors
if (warning.code === "SOURCEMAP_ERROR") {
return;
}
return handler(warning);
},
input: {
"server-entry": "fresh:server_entry",
},
},
},
},
},
};
},
async configResolved(vConfig) {
// Run update check in background
updateCheck(UPDATE_INTERVAL).catch(() => {});
fConfig.islandsDir = pathWithRoot(fConfig.islandsDir, vConfig.root);
fConfig.routeDir = pathWithRoot(fConfig.routeDir, vConfig.root);
config?.islandSpecifiers?.map((spec) => {
const specName = specToName(spec);
const name = fConfig.namer.getUniqueName(specName);
fConfig.islandSpecifiers.set(spec, name);
});
const envDir = pathWithRoot(
vConfig.envDir || vConfig.root,
vConfig.root,
);
await loadEnvFile(path.join(envDir, ".env"));
await loadEnvFile(path.join(envDir, ".env.local"));
const mode = isDev ? "development" : "production";
await loadEnvFile(path.join(envDir, `.env.${mode}`));
await loadEnvFile(path.join(envDir, `.env.${mode}.local`));
},
},
serverEntryPlugin(fConfig),
patches(),
...serverSnapshot(fConfig),
clientEntryPlugin(fConfig),
...clientSnapshot(fConfig),
buildIdPlugin(),
...devServer(),
prefresh({
include: [/\.[cm]?[tj]sx?$/],
exclude: [/node_modules/, /[\\/]+deno[\\/]+npm[\\/]+/],
parserPlugins: [
"importMeta",
"explicitResourceManagement",
"topLevelAwait",
],
}),
checkImports({ checks: fConfig.checkImports }),
];
if (typeof process.versions.deno === "string") {
plugins.push(deno());
}
return plugins;
}
async function loadEnvFile(envPath: string) {
try {
await stdLoadEnv({ envPath, export: true });
} catch {
// Ignore
}
}