-
-
Notifications
You must be signed in to change notification settings - Fork 26
/
index.ts
276 lines (253 loc) · 6.6 KB
/
index.ts
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
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 { PrerenderPlugin, HTMLRoutingMiddlewarePlugin } from "./prerender.js";
import { transformAsync } from "@babel/core";
export type BabelOptions = Omit<
TransformOptions,
| "ast"
| "filename"
| "root"
| "sourceFileName"
| "sourceMaps"
| "inputSourceMap"
>;
export interface PreactPluginOptions {
/**
* Inject devtools bridge in production bundle instead of only in development mode.
* @default false
*/
devtoolsInProd?: boolean;
/**
* Whether to use Preact devtools
* @default true
*/
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({
devtoolsInProd,
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: boolean;
const shouldTransform = createFilter(
include || [/\.[cm]?[tj]sx?$/],
exclude || [/node_modules/],
);
devtoolsInProd = devtoolsInProd ?? false;
prefreshEnabled = prefreshEnabled ?? true;
reactAliasesEnabled = reactAliasesEnabled ?? true;
prerender = prerender ?? { enabled: false };
const jsxPlugin: Plugin = {
name: "vite:preact-jsx",
enforce: "pre",
config() {
return {
build: {
rollupOptions: {
onwarn(warning, warn) {
// Silence Rollup's module-level directive warnings -- they're likely
// to all come from `node_modules` (RSCs) and won't be actionable.
if (warning.code === "MODULE_LEVEL_DIRECTIVE") return;
warn(warning);
},
},
},
// While this config is unconditional, it'll only be used if Babel is not
esbuild: {
jsx: "automatic",
jsxImportSource: jsxImportSource ?? "preact",
},
optimizeDeps: {
include: ["preact", "preact/jsx-runtime", "preact/jsx-dev-runtime"],
},
};
},
configResolved(resolvedConfig) {
config = resolvedConfig;
devToolsEnabled =
devToolsEnabled ?? (!config.isProduction || devtoolsInProd);
useBabel =
!config.isProduction || devToolsEnabled || typeof babel !== "undefined";
},
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",
!id.endsWith(".ts") && "jsx",
/\.tsx?$/.test(id) && "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
? "@babel/plugin-transform-react-jsx"
: "@babel/plugin-transform-react-jsx-development",
{
runtime: "automatic",
importSource: jsxImportSource ?? "preact",
},
],
...(devToolsEnabled ? ["babel-plugin-transform-hook-names"] : []),
],
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: "preact/compat",
},
},
};
},
},
]
: []),
jsxPlugin,
preactDevtoolsPlugin({
devtoolsInProd,
devToolsEnabled,
shouldTransform,
}),
...(prefreshEnabled
? [prefresh({ include, exclude, parserPlugins: baseParserOptions })]
: []),
...(prerender.enabled ? [PrerenderPlugin(prerender)] : []),
...(prerender.previewMiddlewareEnabled
? [
HTMLRoutingMiddlewarePlugin({
fallback: prerender.previewMiddlewareFallback,
}),
]
: []),
];
}
export default preactPlugin;
export { preactPlugin as preact };