-
Notifications
You must be signed in to change notification settings - Fork 54
/
Copy pathindex.ts
403 lines (354 loc) · 12.8 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
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
import * as babel from '@babel/core';
import solid from 'babel-preset-solid';
import { readFileSync } from 'fs';
import { mergeAndConcat } from 'merge-anything';
import { createRequire } from 'module';
import solidRefresh from 'solid-refresh/babel';
import type { Alias, AliasOptions, FilterPattern, Plugin } from 'vite';
import { createFilter, version } from 'vite';
import { crawlFrameworkPkgs } from 'vitefu';
const require = createRequire(import.meta.url);
const runtimePublicPath = '/@solid-refresh';
const runtimeFilePath = require.resolve('solid-refresh/dist/solid-refresh.mjs');
const runtimeCode = readFileSync(runtimeFilePath, 'utf-8');
const isVite6 = version.startsWith('6.');
/** Possible options for the extensions property */
export interface ExtensionOptions {
typescript?: boolean;
}
/** Configuration options for vite-plugin-solid. */
export interface Options {
/**
* A [picomatch](https://github.com/micromatch/picomatch) pattern, or array of patterns, which specifies the files
* the plugin should operate on.
*/
include?: FilterPattern;
/**
* A [picomatch](https://github.com/micromatch/picomatch) pattern, or array of patterns, which specifies the files
* to be ignored by the plugin.
*/
exclude?: FilterPattern;
/**
* This will inject solid-js/dev in place of solid-js in dev mode. Has no
* effect in prod. If set to `false`, it won't inject it in dev. This is
* useful for extra logs and debugging.
*
* @default true
*/
dev?: boolean;
/**
* This will force SSR code in the produced files.
*
* @default false
*/
ssr?: boolean;
/**
* This will inject HMR runtime in dev mode. Has no effect in prod. If
* set to `false`, it won't inject the runtime in dev.
*
* @default true
*/
hot?: boolean;
/**
* This registers additional extensions that should be processed by
* vite-plugin-solid.
*
* @default undefined
*/
extensions?: (string | [string, ExtensionOptions])[];
/**
* Pass any additional babel transform options. They will be merged with
* the transformations required by Solid.
*
* @default {}
*/
babel?:
| babel.TransformOptions
| ((source: string, id: string, ssr: boolean) => babel.TransformOptions)
| ((source: string, id: string, ssr: boolean) => Promise<babel.TransformOptions>);
/**
* Pass any additional [babel-plugin-jsx-dom-expressions](https://github.com/ryansolid/dom-expressions/tree/main/packages/babel-plugin-jsx-dom-expressions#plugin-options).
* They will be merged with the defaults sets by [babel-preset-solid](https://github.com/solidjs/solid/blob/main/packages/babel-preset-solid/index.js#L8-L25).
*
* @default {}
*/
solid?: {
/**
* Removed unnecessary closing tags from template strings. More info here:
* https://github.com/solidjs/solid/blob/main/CHANGELOG.md#smaller-templates
*
* @default false
*/
omitNestedClosingTags?: boolean;
/**
* The name of the runtime module to import the methods from.
*
* @default "solid-js/web"
*/
moduleName?: string;
/**
* The output mode of the compiler.
* Can be:
* - "dom" is standard output
* - "ssr" is for server side rendering of strings.
* - "universal" is for using custom renderers from solid-js/universal
*
* @default "dom"
*/
generate?: 'ssr' | 'dom' | 'universal';
/**
* Indicate whether the output should contain hydratable markers.
*
* @default false
*/
hydratable?: boolean;
/**
* Boolean to indicate whether to enable automatic event delegation on camelCase.
*
* @default true
*/
delegateEvents?: boolean;
/**
* Boolean indicates whether smart conditional detection should be used.
* This optimizes simple boolean expressions and ternaries in JSX.
*
* @default true
*/
wrapConditionals?: boolean;
/**
* Boolean indicates whether to set current render context on Custom Elements and slots.
* Useful for seemless Context API with Web Components.
*
* @default true
*/
contextToCustomElements?: boolean;
/**
* Array of Component exports from module, that aren't included by default with the library.
* This plugin will automatically import them if it comes across them in the JSX.
*
* @default ["For","Show","Switch","Match","Suspense","SuspenseList","Portal","Index","Dynamic","ErrorBoundary"]
*/
builtIns?: string[];
};
}
function getExtension(filename: string): string {
const index = filename.lastIndexOf('.');
return index < 0 ? '' : filename.substring(index).replace(/\?.+$/, '');
}
function containsSolidField(fields: Record<string, any>) {
const keys = Object.keys(fields);
for (let i = 0; i < keys.length; i++) {
const key = keys[i];
if (key === 'solid') return true;
if (typeof fields[key] === 'object' && fields[key] != null && containsSolidField(fields[key]))
return true;
}
return false;
}
function getJestDomExport(setupFiles: string[]) {
return setupFiles?.some((path) => /jest-dom/.test(path))
? undefined
: ['@testing-library/jest-dom/vitest', '@testing-library/jest-dom/extend-expect'].find(
(path) => {
try {
require.resolve(path);
return true;
} catch (e) {
return false;
}
},
);
}
export default function solidPlugin(options: Partial<Options> = {}): Plugin {
const filter = createFilter(options.include, options.exclude);
let needHmr = false;
let replaceDev = false;
let projectRoot = process.cwd();
let isTestMode = false;
return {
name: 'solid',
enforce: 'pre',
async config(userConfig, { command }) {
// We inject the dev mode only if the user explicitly wants it or if we are in dev (serve) mode
replaceDev = options.dev === true || (options.dev !== false && command === 'serve');
projectRoot = userConfig.root;
isTestMode = userConfig.mode === 'test';
if (!userConfig.resolve) userConfig.resolve = {};
userConfig.resolve.alias = normalizeAliases(userConfig.resolve && userConfig.resolve.alias);
const solidPkgsConfig = await crawlFrameworkPkgs({
viteUserConfig: userConfig,
root: projectRoot || process.cwd(),
isBuild: command === 'build',
isFrameworkPkgByJson(pkgJson) {
return containsSolidField(pkgJson.exports || {});
},
});
// fix for bundling dev in production
const nestedDeps = replaceDev
? ['solid-js', 'solid-js/web', 'solid-js/store', 'solid-js/html', 'solid-js/h']
: [];
const userTest = (userConfig as any).test ?? {};
const test = {} as any;
if (userConfig.mode === 'test') {
// to simplify the processing of the config, we normalize the setupFiles to an array
const userSetupFiles: string[] =
typeof userTest.setupFiles === 'string'
? [userTest.setupFiles]
: userTest.setupFiles || [];
if (!userTest.environment && !options.ssr) {
test.environment = 'jsdom';
}
if (
!userTest.server?.deps?.external?.find((item: string | RegExp) =>
/solid-js/.test(item.toString()),
)
) {
test.server = { deps: { external: [/solid-js/] } };
}
if (!userTest.browser?.enabled) {
// vitest browser mode already has bundled jest-dom assertions
// https://main.vitest.dev/guide/browser/assertion-api.html#assertion-api
const jestDomImport = getJestDomExport(userSetupFiles);
if (jestDomImport) {
test.setupFiles = [jestDomImport];
}
}
}
return {
/**
* We only need esbuild on .ts or .js files.
* .tsx & .jsx files are handled by us
*/
// esbuild: { include: /\.ts$/ },
resolve: {
conditions: isVite6
? undefined
: [
'solid',
...(replaceDev ? ['development'] : []),
...(userConfig.mode === 'test' && !options.ssr ? ['browser'] : []),
],
dedupe: nestedDeps,
alias: [{ find: /^solid-refresh$/, replacement: runtimePublicPath }],
},
optimizeDeps: {
include: [...nestedDeps, ...solidPkgsConfig.optimizeDeps.include],
exclude: solidPkgsConfig.optimizeDeps.exclude,
},
ssr: solidPkgsConfig.ssr,
...(test.server ? { test } : {}),
};
},
// @ts-ignore This hook only works in Vite 6
async configEnvironment(name, config, opts) {
config.resolve ??= {};
// Emulate Vite default fallback for `resolve.conditions` if not set
if (config.resolve.conditions == null) {
// @ts-ignore These exports only exist in Vite 6
const { defaultClientConditions, defaultServerConditions } = await import('vite');
if (config.consumer === 'client' || name === 'client' || opts.isSsrTargetWebworker) {
config.resolve.conditions = [...defaultClientConditions];
} else {
config.resolve.conditions = [...defaultServerConditions];
}
}
config.resolve.conditions = [
'solid',
...(replaceDev ? ['development'] : []),
...(isTestMode && !opts.isSsrTargetWebworker ? ['browser'] : []),
...config.resolve.conditions,
];
},
configResolved(config) {
needHmr = config.command === 'serve' && config.mode !== 'production' && options.hot !== false;
},
resolveId(id) {
if (id === runtimePublicPath) return id;
},
load(id) {
if (id === runtimePublicPath) return runtimeCode;
},
async transform(source, id, transformOptions) {
const isSsr = transformOptions && transformOptions.ssr;
const currentFileExtension = getExtension(id);
const extensionsToWatch = options.extensions || [];
const allExtensions = extensionsToWatch.map((extension) =>
// An extension can be a string or a tuple [extension, options]
typeof extension === 'string' ? extension : extension[0],
);
if (!filter(id)) {
return null;
}
id = id.replace(/\?.*$/, '');
if (!(/\.[mc]?[tj]sx$/i.test(id) || allExtensions.includes(currentFileExtension))) {
return null;
}
const inNodeModules = /node_modules/.test(id);
let solidOptions: { generate: 'ssr' | 'dom'; hydratable: boolean };
if (options.ssr) {
if (isSsr) {
solidOptions = { generate: 'ssr', hydratable: true };
} else {
solidOptions = { generate: 'dom', hydratable: true };
}
} else {
solidOptions = { generate: 'dom', hydratable: false };
}
// We need to know if the current file extension has a typescript options tied to it
const shouldBeProcessedWithTypescript =
/\.[mc]?tsx$/i.test(id) ||
extensionsToWatch.some((extension) => {
if (typeof extension === 'string') {
return extension.includes('tsx');
}
const [extensionName, extensionOptions] = extension;
if (extensionName !== currentFileExtension) return false;
return extensionOptions.typescript;
});
const plugins: NonNullable<NonNullable<babel.TransformOptions['parserOpts']>['plugins']> = [
'jsx',
];
if (shouldBeProcessedWithTypescript) {
plugins.push('typescript');
}
const opts: babel.TransformOptions = {
root: projectRoot,
filename: id,
sourceFileName: id,
presets: [[solid, { ...solidOptions, ...(options.solid || {}) }]],
plugins: needHmr && !isSsr && !inNodeModules ? [[solidRefresh, { bundler: 'vite' }]] : [],
ast: false,
sourceMaps: true,
configFile: false,
babelrc: false,
parserOpts: {
plugins,
},
};
// Default value for babel user options
let babelUserOptions: babel.TransformOptions = {};
if (options.babel) {
if (typeof options.babel === 'function') {
const babelOptions = options.babel(source, id, isSsr);
babelUserOptions = babelOptions instanceof Promise ? await babelOptions : babelOptions;
} else {
babelUserOptions = options.babel;
}
}
const babelOptions = mergeAndConcat(babelUserOptions, opts) as babel.TransformOptions;
const { code, map } = await babel.transformAsync(source, babelOptions);
return { code, map };
},
};
}
/**
* This basically normalize all aliases of the config into
* the array format of the alias.
*
* eg: alias: { '@': 'src/' } => [{ find: '@', replacement: 'src/' }]
*/
function normalizeAliases(alias: AliasOptions = []): Alias[] {
return Array.isArray(alias)
? alias
: Object.entries(alias).map(([find, replacement]) => ({ find, replacement }));
}