/
options.ts
474 lines (434 loc) · 14.4 KB
/
options.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
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
/* eslint-disable no-unused-vars */
import { ConfigEnv, UserConfig, ViteDevServer, normalizePath } from 'vite';
import { log } from './log';
import { loadSvelteConfig } from './load-svelte-config';
import { SVELTE_HMR_IMPORTS, SVELTE_IMPORTS, SVELTE_RESOLVE_MAIN_FIELDS } from './constants';
// eslint-disable-next-line node/no-missing-import
import { CompileOptions, Warning } from 'svelte/types/compiler/interfaces';
import {
MarkupPreprocessor,
Preprocessor,
PreprocessorGroup,
Processed
// eslint-disable-next-line node/no-missing-import
} from 'svelte/types/compiler/preprocess';
import path from 'path';
import { findRootSvelteDependencies, needsOptimization, SvelteDependency } from './dependencies';
import { DepOptimizationOptions } from 'vite/src/node/optimizer/index';
import { createRequire } from 'module';
const knownOptions = new Set([
'configFile',
'include',
'exclude',
'extensions',
'emitCss',
'compilerOptions',
'onwarn',
'preprocess',
'hot',
'ignorePluginPreprocessors',
'disableDependencyReinclusion',
'experimental'
]);
function buildDefaultOptions(isProduction: boolean, options: Partial<Options>): Partial<Options> {
// emit for prod, emit in dev unless css hmr is disabled
const emitCss = options?.emitCss != null ? options.emitCss : true;
// no hmr in prod, only inject css in dev if emitCss is false
const hot = isProduction
? false
: {
injectCss: !emitCss
};
const defaultOptions: Partial<Options> = {
extensions: ['.svelte'],
hot,
emitCss,
compilerOptions: {
format: 'esm',
css: !emitCss,
dev: !isProduction
}
};
log.debug(`default options for ${isProduction ? 'production' : 'development'}`, defaultOptions);
return defaultOptions;
}
export function validateInlineOptions(inlineOptions?: Partial<Options>) {
const invalidKeys = Object.keys(inlineOptions || {}).filter((key) => !knownOptions.has(key));
if (invalidKeys.length) {
log.warn(`invalid plugin options "${invalidKeys.join(', ')}" in config`, inlineOptions);
}
}
function enforceOptionsForHmr(options: ResolvedOptions) {
if (options.hot) {
if (!options.compilerOptions.dev) {
log.warn('hmr is enabled but compilerOptions.dev is false, forcing it to true');
options.compilerOptions.dev = true;
}
if (options.emitCss) {
if (options.hot !== true && options.hot.injectCss) {
log.warn('hmr and emitCss are enabled but hot.injectCss is true, forcing it to false');
options.hot.injectCss = false;
}
if (options.compilerOptions.css) {
log.warn(
'hmr and emitCss are enabled but compilerOptions.css is true, forcing it to false'
);
options.compilerOptions.css = false;
}
} else {
if (options.hot === true || !options.hot.injectCss) {
log.warn(
'hmr with emitCss disabled requires option hot.injectCss to be enabled, forcing it to true'
);
if (options.hot === true) {
options.hot = { injectCss: true };
} else {
options.hot.injectCss = true;
}
}
if (!options.compilerOptions.css) {
log.warn(
'hmr with emitCss disabled requires compilerOptions.css to be enabled, forcing it to true'
);
options.compilerOptions.css = true;
}
}
}
}
function enforceOptionsForProduction(options: ResolvedOptions) {
if (options.isProduction) {
if (options.hot) {
log.warn('options.hot is enabled but does not work on production build, forcing it to false');
options.hot = false;
}
if (options.compilerOptions.dev) {
log.warn(
'you are building for production but compilerOptions.dev is true, forcing it to false'
);
options.compilerOptions.dev = false;
}
}
}
function mergeOptions(
defaultOptions: Partial<Options>,
svelteConfig: Partial<Options>,
inlineOptions: Partial<Options>,
viteConfig: UserConfig,
viteEnv: ConfigEnv
): ResolvedOptions {
const merged = {
...defaultOptions,
...svelteConfig,
...inlineOptions,
compilerOptions: {
...defaultOptions.compilerOptions,
...(svelteConfig?.compilerOptions || {}),
...(inlineOptions?.compilerOptions || {})
},
experimental: {
...(svelteConfig?.experimental || {}),
...(inlineOptions?.experimental || {})
},
root: viteConfig.root!,
isProduction: viteEnv.mode === 'production',
isBuild: viteEnv.command === 'build',
isServe: viteEnv.command === 'serve'
};
// configFile of svelteConfig contains the absolute path it was loaded from,
// prefer it over the possibly relative inline path
if (svelteConfig?.configFile) {
merged.configFile = svelteConfig.configFile;
}
return merged;
}
export async function resolveOptions(
inlineOptions: Partial<Options> = {},
viteConfig: UserConfig,
viteEnv: ConfigEnv
): Promise<ResolvedOptions> {
const viteConfigWithResolvedRoot = {
...viteConfig,
root: resolveViteRoot(viteConfig)
};
const defaultOptions = buildDefaultOptions(viteEnv.mode === 'production', inlineOptions);
const svelteConfig = (await loadSvelteConfig(viteConfigWithResolvedRoot, inlineOptions)) || {};
const resolvedOptions = mergeOptions(
defaultOptions,
svelteConfig,
inlineOptions,
viteConfigWithResolvedRoot,
viteEnv
);
enforceOptionsForProduction(resolvedOptions);
enforceOptionsForHmr(resolvedOptions);
return resolvedOptions;
}
// vite passes unresolved `root`option to config hook but we need the resolved value, so do it here
// https://github.com/sveltejs/vite-plugin-svelte/issues/113
// https://github.com/vitejs/vite/blob/43c957de8a99bb326afd732c962f42127b0a4d1e/packages/vite/src/node/config.ts#L293
function resolveViteRoot(viteConfig: UserConfig): string | undefined {
return normalizePath(viteConfig.root ? path.resolve(viteConfig.root) : process.cwd());
}
export function buildExtraViteConfig(
options: ResolvedOptions,
config: UserConfig,
configEnv: ConfigEnv
): Partial<UserConfig> {
// extra handling for svelte dependencies in the project
const svelteDeps = findRootSvelteDependencies(options.root);
const extraViteConfig: Partial<UserConfig> = {
resolve: {
mainFields: [...SVELTE_RESOLVE_MAIN_FIELDS],
dedupe: [...SVELTE_IMPORTS, ...SVELTE_HMR_IMPORTS]
}
// this option is still awaiting a PR in vite to be supported
// see https://github.com/sveltejs/vite-plugin-svelte/issues/60
// @ts-ignore
// knownJsSrcExtensions: options.extensions
};
if (configEnv.command === 'serve') {
extraViteConfig.optimizeDeps = buildOptimizeDepsForSvelte(
svelteDeps,
options,
config.optimizeDeps
);
}
// @ts-ignore
extraViteConfig.ssr = buildSSROptionsForSvelte(svelteDeps, options, config);
return extraViteConfig;
}
function buildOptimizeDepsForSvelte(
svelteDeps: SvelteDependency[],
options: ResolvedOptions,
optimizeDeps?: DepOptimizationOptions
): DepOptimizationOptions {
// include svelte imports for optimization unless explicitly excluded
const include: string[] = [];
const exclude: string[] = ['svelte-hmr'];
const isIncluded = (dep: string) => include.includes(dep) || optimizeDeps?.include?.includes(dep);
const isExcluded = (dep: string) => {
return (
exclude.includes(dep) ||
// vite optimizeDeps.exclude works for subpackages too
// see https://github.com/vitejs/vite/blob/c87763c1418d1ba876eae13d139eba83ac6f28b2/packages/vite/src/node/optimizer/scan.ts#L293
optimizeDeps?.exclude?.some((id) => dep === id || id.startsWith(`${dep}/`))
);
};
if (!isExcluded('svelte')) {
const svelteImportsToInclude = SVELTE_IMPORTS.filter((x) => x !== 'svelte/ssr'); // not used on clientside
log.debug(
`adding bare svelte packages to optimizeDeps.include: ${svelteImportsToInclude.join(', ')} `
);
include.push(...svelteImportsToInclude.filter((x) => !isIncluded(x)));
} else {
log.debug('"svelte" is excluded in optimizeDeps.exclude, skipped adding it to include.');
}
const svelteDepsToExclude = Array.from(new Set(svelteDeps.map((dep) => dep.name))).filter(
(dep) => !isIncluded(dep)
);
log.debug(`automatically excluding found svelte dependencies: ${svelteDepsToExclude.join(', ')}`);
exclude.push(...svelteDepsToExclude.filter((x) => !isExcluded(x)));
if (options.disableDependencyReinclusion !== true) {
const disabledReinclusions = options.disableDependencyReinclusion || [];
if (disabledReinclusions.length > 0) {
log.debug(`not reincluding transitive dependencies of`, disabledReinclusions);
}
const transitiveDepsToInclude = svelteDeps
.filter((dep) => !disabledReinclusions.includes(dep.name) && isExcluded(dep.name))
.flatMap((dep) => {
const localRequire = createRequire(`${dep.dir}/package.json`);
return Object.keys(dep.pkg.dependencies || {})
.filter((depOfDep) => !isExcluded(depOfDep) && needsOptimization(depOfDep, localRequire))
.map((depOfDep) => dep.path.concat(dep.name, depOfDep).join(' > '));
});
log.debug(
`reincluding transitive dependencies of excluded svelte dependencies`,
transitiveDepsToInclude
);
include.push(...transitiveDepsToInclude);
}
return { include, exclude };
}
function buildSSROptionsForSvelte(
svelteDeps: SvelteDependency[],
options: ResolvedOptions,
config: UserConfig
): any {
const noExternal: string[] = [];
// add svelte to ssr.noExternal unless it is present in ssr.external
// so we can resolve it with svelte/ssr
if (options.isBuild && config.build?.ssr) {
// @ts-ignore
if (!config.ssr?.external?.includes('svelte')) {
noExternal.push('svelte');
}
}
// add svelte dependencies to ssr.noExternal unless present in ssr.external or optimizeDeps.include
noExternal.push(
...Array.from(new Set(svelteDeps.map((s) => s.name))).filter((x) => {
// @ts-ignore
return !config.ssr?.external?.includes(x) && !config.optimizeDeps?.include?.includes(x);
})
);
return {
noExternal
};
}
export interface Options {
/**
* Path to a svelte config file, either absolute or relative to Vite root
*
* @see https://vitejs.dev/config/#root
*/
configFile?: string;
/**
* A `minimatch` pattern, or array of patterns, which specifies the files the plugin should
* operate on. By default, all svelte files are included.
*
* @see https://github.com/isaacs/minimatch
*/
include?: Arrayable<string>;
/**
* A `minimatch` pattern, or array of patterns, which specifies the files to be ignored by the
* plugin. By default, no files are ignored.
*
* @see https://github.com/isaacs/minimatch
*/
exclude?: Arrayable<string>;
/**
* A list of file extensions to be compiled by Svelte
*
* @default ['.svelte']
*/
extensions?: string[];
/**
* An array of preprocessors to transform the Svelte source code before compilation
*
* @see https://svelte.dev/docs#svelte_preprocess
*/
preprocess?: Arrayable<PreprocessorGroup>;
/**
* Emit Svelte styles as virtual CSS files for Vite and other plugins to process
*
* @default true
*/
emitCss?: boolean;
/**
* The options to be passed to the Svelte compiler
*
* @see https://svelte.dev/docs#svelte_compile
*/
compilerOptions?: CompileOptions;
/**
* Handles warning emitted from the Svelte compiler
*/
onwarn?: (warning: Warning, defaultHandler?: (warning: Warning) => void) => void;
/**
* Enable or disable Hot Module Replacement.
*
* !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
*
* DO NOT CUSTOMIZE SVELTE-HMR OPTIONS UNLESS YOU KNOW EXACTLY WHAT YOU ARE DOING
*
* YOU HAVE BEEN WARNED
*
* !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
*
* Set an object to pass custom options to svelte-hmr
*
* @see https://github.com/rixo/svelte-hmr#options
* @default true for development, always false for production
*/
hot?: boolean | { injectCss?: boolean; [key: string]: any };
/**
* Some Vite plugins can contribute additional preprocessors by defining `api.sveltePreprocess`.
* If you don't want to use them, set this to true to ignore them all or use an array of strings
* with plugin names to specify which.
*
* @default false
*/
ignorePluginPreprocessors?: boolean | string[];
/**
* vite-plugin-svelte automatically handles excluding svelte libraries and reinclusion of their dependencies
* in vite.optimizeDeps.
*
* `disableDependencyReinclusion: true` disables all reinclusions
* `disableDependencyReinclusion: ['foo','bar']` disables reinclusions for dependencies of foo and bar
*
* This should be used for hybrid packages that contain both node and browser dependencies, eg Routify
*
* @default false
*/
disableDependencyReinclusion?: boolean | string[];
/**
* These options are considered experimental and breaking changes to them can occur in any release
*/
experimental?: ExperimentalOptions;
}
/**
* These options are considered experimental and breaking changes to them can occur in any release
*/
export interface ExperimentalOptions {
/**
* Use extra preprocessors that delegate style and TypeScript preprocessing to native Vite plugins
*
* Do not use together with `svelte-preprocess`!
*
* @default false
*/
useVitePreprocess?: boolean;
/**
* If a preprocessor does not provide a sourcemap, a best-effort fallback sourcemap will be provided.
* This option requires `diff-match-patch` to be installed as a peer dependency.
*
* @see https://github.com/google/diff-match-patch
* @default false
*/
generateMissingPreprocessorSourcemaps?: boolean;
/**
* A function to update `compilerOptions` before compilation
*
* `data.filename` - The file to be compiled
* `data.code` - The preprocessed Svelte code
* `data.compileOptions` - The current compiler options
*
* To change part of the compiler options, return an object with the changes you need.
*
* @example
* ```
* ({ filename, compileOptions }) => {
* // Dynamically set hydration per Svelte file
* if (compileWithHydratable(filename) && !compileOptions.hydratable) {
* return { hydratable: true };
* }
* }
* ```
*/
dynamicCompileOptions?: (data: {
filename: string;
code: string;
compileOptions: Partial<CompileOptions>;
}) => Promise<Partial<CompileOptions> | void> | Partial<CompileOptions> | void;
}
export interface ResolvedOptions extends Options {
// these options are non-nullable after resolve
compilerOptions: CompileOptions;
experimental: ExperimentalOptions;
// extra options
root: string;
isProduction: boolean;
isBuild: boolean;
isServe: boolean;
server?: ViteDevServer;
}
export type {
CompileOptions,
Processed,
MarkupPreprocessor,
Preprocessor,
PreprocessorGroup,
Warning
};
export type ModuleFormat = NonNullable<CompileOptions['format']>;
export type CssHashGetter = NonNullable<CompileOptions['cssHash']>;
export type Arrayable<T> = T | T[];