-
-
Notifications
You must be signed in to change notification settings - Fork 34
Expand file tree
/
Copy pathindex.ts
More file actions
291 lines (268 loc) · 7.46 KB
/
index.ts
File metadata and controls
291 lines (268 loc) · 7.46 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
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
import type { Plugin, ResolvedConfig } from "vite";
import type { FilterPattern } from "@rollup/pluginutils";
import type { ParserPlugin, ParserOptions } from "@babel/parser";
import type { TransformOptions } from "@babel/core";
import prefresh from "@prefresh/vite";
import { preactDevtoolsPlugin } from "./devtools.js";
import { createFilter, parseId } from "./utils.js";
import { vitePrerenderPlugin } from "vite-prerender-plugin";
import { transformAsync } from "@babel/core";
// @ts-ignore package doesn't ship with declaration files
import babelReactJsx from "@babel/plugin-transform-react-jsx";
// @ts-ignore package doesn't ship with declaration files
import babelReactJsxDev from "@babel/plugin-transform-react-jsx-development";
// @ts-ignore package doesn't ship with declaration files
import babelHookNames from "babel-plugin-transform-hook-names";
export type BabelOptions = Omit<
TransformOptions,
| "ast"
| "filename"
| "root"
| "sourceFileName"
| "sourceMaps"
| "inputSourceMap"
>;
export interface PreactPluginOptions {
/**
* Whether to use Preact devtools
* @default !isProduction
*/
devToolsEnabled?: boolean;
/**
* Whether to use prefresh HMR
* @default true
*/
prefreshEnabled?: boolean;
/**
* Whether to alias react, react-dom to preact/compat
* @default true
*/
reactAliasesEnabled?: boolean;
/**
* Prerender plugin options
*/
prerender?: {
/**
* Whether to prerender your app on build
*/
enabled: boolean;
/**
* Absolute path to script containing an exported `prerender()` function
*/
prerenderScript?: string;
/**
* Query selector for specifying where to insert prerender result in your HTML template
*/
renderTarget?: string;
/**
* Additional routes that should be prerendered
*/
additionalPrerenderRoutes?: string[];
/**
* Vite's preview server won't use our prerendered HTML by default, this middleware correct this
*/
previewMiddlewareEnabled?: boolean;
/**
* Path to use as a fallback/404 route, i.e., `/404` or `/not-found`
*/
previewMiddlewareFallback?: string;
};
/**
* RegExp or glob to match files to be transformed
*/
include?: FilterPattern;
/**
* RegExp or glob to match files to NOT be transformed
*/
exclude?: FilterPattern;
/**
* Babel configuration applied in both dev and prod.
*/
babel?: BabelOptions;
/**
* Import Source for jsx. Defaults to "preact".
*/
jsxImportSource?: string;
}
export interface PreactBabelOptions extends BabelOptions {
plugins: Extract<BabelOptions["plugins"], any[]>;
presets: Extract<BabelOptions["presets"], any[]>;
overrides: Extract<BabelOptions["overrides"], any[]>;
parserOpts: ParserOptions & {
plugins: Extract<ParserOptions["plugins"], any[]>;
};
}
// Taken from https://github.com/vitejs/vite/blob/main/packages/plugin-react/src/index.ts
function preactPlugin({
devToolsEnabled,
prefreshEnabled,
reactAliasesEnabled,
prerender,
include,
exclude,
babel,
jsxImportSource,
}: PreactPluginOptions = {}): Plugin[] {
const baseParserOptions = [
"importMeta",
"explicitResourceManagement",
"topLevelAwait",
];
let config: ResolvedConfig;
let babelOptions = {
babelrc: false,
configFile: false,
...babel,
} as PreactBabelOptions;
babelOptions.plugins ||= [];
babelOptions.presets ||= [];
babelOptions.overrides ||= [];
babelOptions.parserOpts ||= {} as any;
babelOptions.parserOpts.plugins ||= [];
let useBabel = typeof babel !== "undefined";
const shouldTransform = createFilter(
include || [/\.[cm]?[tj]sx?$/],
exclude || [/node_modules/],
);
prefreshEnabled = prefreshEnabled ?? true;
reactAliasesEnabled = reactAliasesEnabled ?? true;
prerender = prerender ?? { enabled: false };
const prerenderPlugin = vitePrerenderPlugin(prerender);
if (!prerender.previewMiddlewareEnabled) {
const idx = prerenderPlugin.findIndex(
p => p.name == "serve-prerendered-html",
);
if (idx > -1) {
prerenderPlugin.splice(idx, 1);
}
}
const jsxPlugin: Plugin = {
name: "vite:preact-jsx",
enforce: "pre",
config() {
return {
build: {
rollupOptions: {
onwarn(warning, warn) {
// Silence Rollup's module-level directive warnings re:"use client".
// They're likely to come from `node_modules` and won't be actionable.
if (
warning.code === "MODULE_LEVEL_DIRECTIVE" &&
warning.message.includes("use client")
)
return;
// ESBuild seemingly doesn't include mappings for directives, causing
// Rollup to emit warnings about missing source locations. This too is
// likely to come from `node_modules` and won't be actionable.
// evanw/esbuild#3548
if (
warning.code === "SOURCEMAP_ERROR" &&
warning.message.includes("resolve original location") &&
warning.pos === 0
)
return;
warn(warning);
},
},
},
esbuild: useBabel
? undefined
: {
jsx: "automatic",
jsxImportSource: jsxImportSource ?? "preact",
},
optimizeDeps: {
include: ["preact", "preact/jsx-runtime", "preact/jsx-dev-runtime"],
},
};
},
configResolved(resolvedConfig) {
config = resolvedConfig;
devToolsEnabled = devToolsEnabled ?? !config.isProduction;
useBabel ||= !config.isProduction || !!devToolsEnabled;
},
async transform(code, url) {
// Ignore query parameters, as in Vue SFC virtual modules.
const { id } = parseId(url);
if (!useBabel || !shouldTransform(id)) return;
const parserPlugins = [
...baseParserOptions,
"classProperties",
"classPrivateProperties",
"classPrivateMethods",
!/\.[cm]?ts$/.test(id) && "jsx",
// Babel doesn't support many transforms without also transforming TS.
// Whilst our limited transforms (JSX & hook names) are fine, if users
// add their own, they may run into unhelpful errors. See #170
/\.[cm]?tsx?$/.test(id) && typeof babel !== "undefined" && "typescript",
].filter(Boolean) as ParserPlugin[];
const result = await transformAsync(code, {
...babelOptions,
ast: true,
root: config.root,
filename: id,
parserOpts: {
...babelOptions.parserOpts,
sourceType: "module",
allowAwaitOutsideFunction: true,
plugins: parserPlugins,
},
generatorOpts: {
...babelOptions.generatorOpts,
decoratorsBeforeExport: true,
},
plugins: [
...babelOptions.plugins,
[
config.isProduction ? babelReactJsx : babelReactJsxDev,
{
runtime: "automatic",
importSource: jsxImportSource ?? "preact",
},
],
...(devToolsEnabled ? [babelHookNames] : []),
],
sourceMaps: true,
inputSourceMap: false as any,
});
// NOTE: Since no config file is being loaded, this path wouldn't occur.
if (!result) return;
return {
code: result.code || code,
map: result.map,
};
},
};
return [
...(reactAliasesEnabled
? [
{
name: "preact:config",
config() {
return {
resolve: {
alias: {
"react-dom/test-utils": "preact/test-utils",
"react-dom": "preact/compat",
"react/jsx-runtime": "preact/jsx-runtime",
react: "preact/compat",
},
},
};
},
},
]
: []),
jsxPlugin,
preactDevtoolsPlugin({
devToolsEnabled,
shouldTransform,
}),
...(prefreshEnabled
? [prefresh({ include, exclude, parserPlugins: baseParserOptions })]
: []),
...(prerender.enabled ? prerenderPlugin : []),
];
}
export default preactPlugin;
export { preactPlugin as preact };