@sveltejs/vite-plugin-svelte 1.1.1 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,15 +1,13 @@
1
1
  /* eslint-disable no-unused-vars */
2
- import {
3
- ConfigEnv,
4
- DepOptimizationOptions,
5
- ResolvedConfig,
6
- UserConfig,
7
- ViteDevServer,
8
- normalizePath
9
- } from 'vite';
2
+ import { ConfigEnv, ResolvedConfig, UserConfig, ViteDevServer, normalizePath } from 'vite';
10
3
  import { log } from './log';
11
4
  import { loadSvelteConfig } from './load-svelte-config';
12
- import { SVELTE_HMR_IMPORTS, SVELTE_IMPORTS, SVELTE_RESOLVE_MAIN_FIELDS } from './constants';
5
+ import {
6
+ SVELTE_EXPORT_CONDITIONS,
7
+ SVELTE_HMR_IMPORTS,
8
+ SVELTE_IMPORTS,
9
+ SVELTE_RESOLVE_MAIN_FIELDS
10
+ } from './constants';
13
11
  // eslint-disable-next-line node/no-missing-import
14
12
  import type { CompileOptions, Warning } from 'svelte/types/compiler/interfaces';
15
13
  import type {
@@ -21,11 +19,23 @@ import type {
21
19
  } from 'svelte/types/compiler/preprocess';
22
20
 
23
21
  import path from 'path';
24
- import { findRootSvelteDependencies, needsOptimization, SvelteDependency } from './dependencies';
25
- import { createRequire } from 'module';
26
22
  import { esbuildSveltePlugin, facadeEsbuildSveltePluginName } from './esbuild';
27
23
  import { addExtraPreprocessors } from './preprocess';
28
24
  import deepmerge from 'deepmerge';
25
+ import {
26
+ crawlFrameworkPkgs,
27
+ isDepExcluded,
28
+ isDepExternaled,
29
+ isDepIncluded,
30
+ isDepNoExternaled
31
+ // eslint-disable-next-line node/no-missing-import
32
+ } from 'vitefu';
33
+ import { atLeastSvelte } from './svelte-version';
34
+ import { isCommonDepWithoutSvelteField } from './dependencies';
35
+ import { VitePluginSvelteStats } from './vite-plugin-svelte-stats';
36
+
37
+ // svelte 3.53.0 changed compilerOptions.css from boolean to string | boolen, use string when available
38
+ const cssAsString = atLeastSvelte('3.53.0');
29
39
 
30
40
  const allowedPluginOptions = new Set([
31
41
  'include',
@@ -125,9 +135,11 @@ export async function preResolveOptions(
125
135
  ...viteUserConfig,
126
136
  root: resolveViteRoot(viteUserConfig)
127
137
  };
138
+ const isBuild = viteEnv.command === 'build';
128
139
  const defaultOptions: Partial<Options> = {
129
140
  extensions: ['.svelte'],
130
- emitCss: true
141
+ emitCss: true,
142
+ prebundleSvelteLibraries: !isBuild
131
143
  };
132
144
  const svelteConfig = convertPluginOptions(
133
145
  await loadSvelteConfig(viteConfigWithResolvedRoot, inlineOptions)
@@ -135,7 +147,7 @@ export async function preResolveOptions(
135
147
 
136
148
  const extraOptions: Partial<PreResolvedOptions> = {
137
149
  root: viteConfigWithResolvedRoot.root!,
138
- isBuild: viteEnv.command === 'build',
150
+ isBuild,
139
151
  isServe: viteEnv.command === 'serve',
140
152
  isDebug: process.env.DEBUG != null
141
153
  };
@@ -170,15 +182,20 @@ export function resolveOptions(
170
182
  preResolveOptions: PreResolvedOptions,
171
183
  viteConfig: ResolvedConfig
172
184
  ): ResolvedOptions {
185
+ const css = cssAsString
186
+ ? preResolveOptions.emitCss
187
+ ? 'external'
188
+ : 'injected'
189
+ : !preResolveOptions.emitCss;
173
190
  const defaultOptions: Partial<Options> = {
174
191
  hot: viteConfig.isProduction
175
192
  ? false
176
193
  : {
177
- injectCss: !preResolveOptions.emitCss,
194
+ injectCss: css === true || css === 'injected',
178
195
  partialAccept: !!viteConfig.experimental?.hmrPartialAccept
179
196
  },
180
197
  compilerOptions: {
181
- css: !preResolveOptions.emitCss,
198
+ css,
182
199
  dev: !viteConfig.isProduction
183
200
  }
184
201
  };
@@ -194,6 +211,14 @@ export function resolveOptions(
194
211
  addExtraPreprocessors(merged, viteConfig);
195
212
  enforceOptionsForHmr(merged);
196
213
  enforceOptionsForProduction(merged);
214
+ // mergeConfigs would mangle functions on the stats class, so do this afterwards
215
+ const isLogLevelInfo = [undefined, 'info'].includes(viteConfig.logLevel);
216
+ const disableCompileStats = merged.experimental?.disableCompileStats;
217
+ const statsEnabled =
218
+ disableCompileStats !== true && disableCompileStats !== (merged.isBuild ? 'build' : 'dev');
219
+ if (statsEnabled && isLogLevelInfo) {
220
+ merged.stats = new VitePluginSvelteStats();
221
+ }
197
222
  return merged;
198
223
  }
199
224
 
@@ -208,11 +233,13 @@ function enforceOptionsForHmr(options: ResolvedOptions) {
208
233
  log.warn('hmr and emitCss are enabled but hot.injectCss is true, forcing it to false');
209
234
  options.hot.injectCss = false;
210
235
  }
211
- if (options.compilerOptions.css) {
236
+ const css = options.compilerOptions.css;
237
+ if (css === true || css === 'injected') {
238
+ const forcedCss = cssAsString ? 'external' : false;
212
239
  log.warn(
213
- 'hmr and emitCss are enabled but compilerOptions.css is true, forcing it to false'
240
+ `hmr and emitCss are enabled but compilerOptions.css is ${css}, forcing it to ${forcedCss}`
214
241
  );
215
- options.compilerOptions.css = false;
242
+ options.compilerOptions.css = forcedCss;
216
243
  }
217
244
  } else {
218
245
  if (options.hot === true || !options.hot.injectCss) {
@@ -225,11 +252,13 @@ function enforceOptionsForHmr(options: ResolvedOptions) {
225
252
  options.hot.injectCss = true;
226
253
  }
227
254
  }
228
- if (!options.compilerOptions.css) {
255
+ const css = options.compilerOptions.css;
256
+ if (!(css === true || css === 'injected')) {
257
+ const forcedCss = cssAsString ? 'injected' : true;
229
258
  log.warn(
230
- 'hmr with emitCss disabled requires compilerOptions.css to be enabled, forcing it to true'
259
+ `hmr with emitCss disabled requires compilerOptions.css to be enabled, forcing it to ${forcedCss}`
231
260
  );
232
- options.compilerOptions.css = true;
261
+ options.compilerOptions.css = forcedCss;
233
262
  }
234
263
  }
235
264
  }
@@ -273,20 +302,9 @@ function removeIgnoredOptions(options: ResolvedOptions) {
273
302
  // some SvelteKit options need compilerOptions to work, so set them here.
274
303
  function addSvelteKitOptions(options: ResolvedOptions) {
275
304
  // @ts-expect-error kit is not typed to avoid dependency on sveltekit
276
- if (options?.kit != null) {
277
- // @ts-expect-error kit is not typed to avoid dependency on sveltekit
278
- const kit_browser_hydrate = options.kit.browser?.hydrate;
279
- const hydratable = kit_browser_hydrate !== false;
280
- if (
281
- options.compilerOptions.hydratable != null &&
282
- options.compilerOptions.hydratable !== hydratable
283
- ) {
284
- log.warn(
285
- `Conflicting values "compilerOptions.hydratable: ${options.compilerOptions.hydratable}" and "kit.browser.hydrate: ${kit_browser_hydrate}" in your svelte config. You should remove "compilerOptions.hydratable".`
286
- );
287
- }
288
- log.debug(`Setting compilerOptions.hydratable: ${hydratable} for SvelteKit`);
289
- options.compilerOptions.hydratable = hydratable;
305
+ if (options?.kit != null && options.compilerOptions.hydratable == null) {
306
+ log.debug(`Setting compilerOptions.hydratable = true for SvelteKit`);
307
+ options.compilerOptions.hydratable = true;
290
308
  }
291
309
  }
292
310
 
@@ -306,16 +324,15 @@ function resolveViteRoot(viteConfig: UserConfig): string | undefined {
306
324
  return normalizePath(viteConfig.root ? path.resolve(viteConfig.root) : process.cwd());
307
325
  }
308
326
 
309
- export function buildExtraViteConfig(
327
+ export async function buildExtraViteConfig(
310
328
  options: PreResolvedOptions,
311
329
  config: UserConfig
312
- ): Partial<UserConfig> {
313
- // extra handling for svelte dependencies in the project
314
- const svelteDeps = findRootSvelteDependencies(options.root);
330
+ ): Promise<Partial<UserConfig>> {
315
331
  const extraViteConfig: Partial<UserConfig> = {
316
332
  resolve: {
317
333
  mainFields: [...SVELTE_RESOLVE_MAIN_FIELDS],
318
- dedupe: [...SVELTE_IMPORTS, ...SVELTE_HMR_IMPORTS]
334
+ dedupe: [...SVELTE_IMPORTS, ...SVELTE_HMR_IMPORTS],
335
+ conditions: [...SVELTE_EXPORT_CONDITIONS]
319
336
  }
320
337
  // this option is still awaiting a PR in vite to be supported
321
338
  // see https://github.com/sveltejs/vite-plugin-svelte/issues/60
@@ -323,12 +340,40 @@ export function buildExtraViteConfig(
323
340
  // knownJsSrcExtensions: options.extensions
324
341
  };
325
342
 
326
- extraViteConfig.optimizeDeps = buildOptimizeDepsForSvelte(
327
- svelteDeps,
328
- options,
329
- config.optimizeDeps
330
- );
343
+ const extraSvelteConfig = buildExtraConfigForSvelte(config);
344
+ const extraDepsConfig = await buildExtraConfigForDependencies(options, config);
345
+ // merge extra svelte and deps config, but make sure dep values are not contradicting svelte
346
+ extraViteConfig.optimizeDeps = {
347
+ include: [
348
+ ...extraSvelteConfig.optimizeDeps.include,
349
+ ...extraDepsConfig.optimizeDeps.include.filter(
350
+ (dep) => !isDepExcluded(dep, extraSvelteConfig.optimizeDeps.exclude)
351
+ )
352
+ ],
353
+ exclude: [
354
+ ...extraSvelteConfig.optimizeDeps.exclude,
355
+ ...extraDepsConfig.optimizeDeps.exclude.filter(
356
+ (dep) => !isDepIncluded(dep, extraSvelteConfig.optimizeDeps.include)
357
+ )
358
+ ]
359
+ };
360
+
361
+ extraViteConfig.ssr = {
362
+ external: [
363
+ ...extraSvelteConfig.ssr.external,
364
+ ...extraDepsConfig.ssr.external.filter(
365
+ (dep) => !isDepNoExternaled(dep, extraSvelteConfig.ssr.noExternal)
366
+ )
367
+ ],
368
+ noExternal: [
369
+ ...extraSvelteConfig.ssr.noExternal,
370
+ ...extraDepsConfig.ssr.noExternal.filter(
371
+ (dep) => !isDepExternaled(dep, extraSvelteConfig.ssr.external)
372
+ )
373
+ ]
374
+ };
331
375
 
376
+ // handle prebundling for svelte files
332
377
  if (options.prebundleSvelteLibraries) {
333
378
  extraViteConfig.optimizeDeps = {
334
379
  ...extraViteConfig.optimizeDeps,
@@ -344,9 +389,6 @@ export function buildExtraViteConfig(
344
389
  };
345
390
  }
346
391
 
347
- // @ts-ignore
348
- extraViteConfig.ssr = buildSSROptionsForSvelte(svelteDeps, options, config, extraViteConfig);
349
-
350
392
  // enable hmrPartialAccept if not explicitly disabled
351
393
  if (
352
394
  (options.hot == null ||
@@ -357,112 +399,136 @@ export function buildExtraViteConfig(
357
399
  log.debug('enabling "experimental.hmrPartialAccept" in vite config');
358
400
  extraViteConfig.experimental = { hmrPartialAccept: true };
359
401
  }
360
-
402
+ validateViteConfig(extraViteConfig, config, options);
361
403
  return extraViteConfig;
362
404
  }
363
405
 
364
- function buildOptimizeDepsForSvelte(
365
- svelteDeps: SvelteDependency[],
366
- options: PreResolvedOptions,
367
- optimizeDeps?: DepOptimizationOptions
368
- ): DepOptimizationOptions {
369
- // include svelte imports for optimization unless explicitly excluded
370
- const include: string[] = [];
371
- const exclude: string[] = ['svelte-hmr'];
372
- const isIncluded = (dep: string) => include.includes(dep) || optimizeDeps?.include?.includes(dep);
373
- const isExcluded = (dep: string) => {
374
- return (
375
- exclude.includes(dep) ||
376
- // vite optimizeDeps.exclude works for subpackages too
377
- // see https://github.com/vitejs/vite/blob/c87763c1418d1ba876eae13d139eba83ac6f28b2/packages/vite/src/node/optimizer/scan.ts#L293
378
- optimizeDeps?.exclude?.some((id: string) => dep === id || id.startsWith(`${dep}/`))
379
- );
380
- };
381
- if (!isExcluded('svelte')) {
382
- const svelteImportsToInclude = SVELTE_IMPORTS.filter((x) => x !== 'svelte/ssr'); // not used on clientside
383
- log.debug(
384
- `adding bare svelte packages to optimizeDeps.include: ${svelteImportsToInclude.join(', ')} `
385
- );
386
- include.push(...svelteImportsToInclude.filter((x) => !isIncluded(x)));
387
- } else {
388
- log.debug('"svelte" is excluded in optimizeDeps.exclude, skipped adding it to include.');
406
+ function validateViteConfig(
407
+ extraViteConfig: Partial<UserConfig>,
408
+ config: UserConfig,
409
+ options: PreResolvedOptions
410
+ ) {
411
+ const { prebundleSvelteLibraries, isBuild } = options;
412
+ if (prebundleSvelteLibraries) {
413
+ const isEnabled = (option: 'dev' | 'build' | boolean) =>
414
+ option !== true && option !== (isBuild ? 'build' : 'dev');
415
+ const logWarning = (name: string, value: 'dev' | 'build' | boolean, recommendation: string) =>
416
+ log.warn.once(
417
+ `Incompatible options: \`prebundleSvelteLibraries: true\` and vite \`${name}: ${JSON.stringify(
418
+ value
419
+ )}\` ${isBuild ? 'during build.' : '.'} ${recommendation}`
420
+ );
421
+ const viteOptimizeDepsDisabled = config.optimizeDeps?.disabled ?? 'build'; // fall back to vite default
422
+ const isOptimizeDepsEnabled = isEnabled(viteOptimizeDepsDisabled);
423
+ if (!isBuild && !isOptimizeDepsEnabled) {
424
+ logWarning(
425
+ 'optimizeDeps.disabled',
426
+ viteOptimizeDepsDisabled,
427
+ 'Forcing `optimizeDeps.disabled: "build"`. Disable prebundleSvelteLibraries or update your vite config to enable optimizeDeps during dev.'
428
+ );
429
+ extraViteConfig.optimizeDeps!.disabled = 'build';
430
+ } else if (isBuild && isOptimizeDepsEnabled) {
431
+ logWarning(
432
+ 'optimizeDeps.disabled',
433
+ viteOptimizeDepsDisabled,
434
+ 'Disable optimizeDeps or prebundleSvelteLibraries for build if you experience errors.'
435
+ );
436
+ }
389
437
  }
438
+ }
439
+
440
+ async function buildExtraConfigForDependencies(options: PreResolvedOptions, config: UserConfig) {
441
+ // extra handling for svelte dependencies in the project
442
+ const depsConfig = await crawlFrameworkPkgs({
443
+ root: options.root,
444
+ isBuild: options.isBuild,
445
+ viteUserConfig: config,
446
+ isFrameworkPkgByJson(pkgJson) {
447
+ let hasSvelteCondition = false;
448
+ if (typeof pkgJson.exports === 'object') {
449
+ // use replacer as a simple way to iterate over nested keys
450
+ JSON.stringify(pkgJson.exports, (key, value) => {
451
+ if (SVELTE_EXPORT_CONDITIONS.includes(key)) {
452
+ hasSvelteCondition = true;
453
+ }
454
+ return value;
455
+ });
456
+ }
457
+ return hasSvelteCondition || !!pkgJson.svelte;
458
+ },
459
+ isSemiFrameworkPkgByJson(pkgJson) {
460
+ return !!pkgJson.dependencies?.svelte || !!pkgJson.peerDependencies?.svelte;
461
+ },
462
+ isFrameworkPkgByName(pkgName) {
463
+ const isNotSveltePackage = isCommonDepWithoutSvelteField(pkgName);
464
+ if (isNotSveltePackage) {
465
+ return false;
466
+ } else {
467
+ return undefined;
468
+ }
469
+ }
470
+ });
471
+
472
+ log.debug('extra config for dependencies generated by vitefu', depsConfig);
390
473
 
391
- // If we prebundle svelte libraries, we can skip the whole prebundling dance below
392
474
  if (options.prebundleSvelteLibraries) {
393
- return { include, exclude };
475
+ // prebundling enabled, so we don't need extra dependency excludes
476
+ depsConfig.optimizeDeps.exclude = [];
477
+ // but keep dependency reinclusions of explicit user excludes
478
+ const userExclude = config.optimizeDeps?.exclude;
479
+ depsConfig.optimizeDeps.include = !userExclude
480
+ ? []
481
+ : depsConfig.optimizeDeps.include.filter((dep: string) => {
482
+ // reincludes look like this: foo > bar > baz
483
+ // in case foo or bar are excluded, we have to retain the reinclude even with prebundling
484
+ return (
485
+ dep.includes('>') &&
486
+ dep
487
+ .split('>')
488
+ .slice(0, -1)
489
+ .some((d) => isDepExcluded(d.trim(), userExclude))
490
+ );
491
+ });
492
+ }
493
+ if (options.disableDependencyReinclusion === true) {
494
+ depsConfig.optimizeDeps.include = depsConfig.optimizeDeps.include.filter(
495
+ (dep) => !dep.includes('>')
496
+ );
497
+ } else if (Array.isArray(options.disableDependencyReinclusion)) {
498
+ const disabledDeps = options.disableDependencyReinclusion;
499
+ depsConfig.optimizeDeps.include = depsConfig.optimizeDeps.include.filter((dep) => {
500
+ if (!dep.includes('>')) return true;
501
+ const trimDep = dep.replace(/\s+/g, '');
502
+ return disabledDeps.some((disabled) => trimDep.includes(`${disabled}>`));
503
+ });
394
504
  }
395
505
 
396
- // only svelte component libraries needs to be processed for optimizeDeps, js libraries work fine
397
- svelteDeps = svelteDeps.filter((dep) => dep.type === 'component-library');
506
+ log.debug('post-processed extra config for dependencies', depsConfig);
398
507
 
399
- const svelteDepsToExclude = Array.from(new Set(svelteDeps.map((dep) => dep.name))).filter(
400
- (dep) => !isIncluded(dep)
401
- );
402
- log.debug(`automatically excluding found svelte dependencies: ${svelteDepsToExclude.join(', ')}`);
403
- exclude.push(...svelteDepsToExclude.filter((x) => !isExcluded(x)));
508
+ return depsConfig;
509
+ }
404
510
 
405
- if (options.disableDependencyReinclusion !== true) {
406
- const disabledReinclusions = options.disableDependencyReinclusion || [];
407
- if (disabledReinclusions.length > 0) {
408
- log.debug(`not reincluding transitive dependencies of`, disabledReinclusions);
409
- }
410
- const transitiveDepsToInclude = svelteDeps
411
- .filter((dep) => !disabledReinclusions.includes(dep.name) && isExcluded(dep.name))
412
- .flatMap((dep) => {
413
- const localRequire = createRequire(`${dep.dir}/package.json`);
414
- return Object.keys(dep.pkg.dependencies || {})
415
- .filter((depOfDep) => !isExcluded(depOfDep) && needsOptimization(depOfDep, localRequire))
416
- .map((depOfDep) => dep.path.concat(dep.name, depOfDep).join(' > '));
417
- });
511
+ function buildExtraConfigForSvelte(config: UserConfig) {
512
+ // include svelte imports for optimization unless explicitly excluded
513
+ const include: string[] = [];
514
+ const exclude: string[] = ['svelte-hmr'];
515
+ if (!isDepExcluded('svelte', config.optimizeDeps?.exclude ?? [])) {
516
+ const svelteImportsToInclude = SVELTE_IMPORTS.filter((x) => x !== 'svelte/ssr'); // not used on clientside
418
517
  log.debug(
419
- `reincluding transitive dependencies of excluded svelte dependencies`,
420
- transitiveDepsToInclude
518
+ `adding bare svelte packages to optimizeDeps.include: ${svelteImportsToInclude.join(', ')} `
421
519
  );
422
- include.push(...transitiveDepsToInclude);
520
+ include.push(...svelteImportsToInclude);
521
+ } else {
522
+ log.debug('"svelte" is excluded in optimizeDeps.exclude, skipped adding it to include.');
423
523
  }
424
-
425
- return { include, exclude };
426
- }
427
-
428
- function buildSSROptionsForSvelte(
429
- svelteDeps: SvelteDependency[],
430
- options: ResolvedOptions,
431
- config: UserConfig
432
- ): any {
433
524
  const noExternal: (string | RegExp)[] = [];
434
-
525
+ const external: string[] = [];
435
526
  // add svelte to ssr.noExternal unless it is present in ssr.external
436
527
  // so we can resolve it with svelte/ssr
437
- if (!config.ssr?.external?.includes('svelte')) {
528
+ if (!isDepExternaled('svelte', config.ssr?.external ?? [])) {
438
529
  noExternal.push('svelte', /^svelte\//);
439
530
  }
440
-
441
- // add svelte dependencies to ssr.noExternal unless present in ssr.external
442
- noExternal.push(
443
- ...Array.from(new Set(svelteDeps.map((s) => s.name))).filter(
444
- (x) => !config.ssr?.external?.includes(x)
445
- )
446
- );
447
- const ssr = {
448
- noExternal,
449
- external: [] as string[]
450
- };
451
-
452
- if (options.isServe) {
453
- // during dev, we have to externalize transitive dependencies, see https://github.com/sveltejs/vite-plugin-svelte/issues/281
454
- ssr.external = Array.from(
455
- new Set(svelteDeps.flatMap((dep) => Object.keys(dep.pkg.dependencies || {})))
456
- ).filter(
457
- (dep) =>
458
- !ssr.noExternal.includes(dep) &&
459
- // TODO noExternal can be something different than a string array
460
- //!config.ssr?.noExternal?.includes(dep) &&
461
- !config.ssr?.external?.includes(dep)
462
- );
463
- }
464
-
465
- return ssr;
531
+ return { optimizeDeps: { include, exclude }, ssr: { noExternal, external } };
466
532
  }
467
533
 
468
534
  export function patchResolvedViteConfig(viteConfig: ResolvedConfig, options: ResolvedOptions) {
@@ -552,9 +618,11 @@ export interface PluginOptions {
552
618
  disableDependencyReinclusion?: boolean | string[];
553
619
 
554
620
  /**
555
- * Force Vite to pre-bundle Svelte libraries
621
+ * Enable support for Vite's dependency optimization to prebundle Svelte libraries.
556
622
  *
557
- * @default false
623
+ * To disable prebundling for a specific library, add it to `optimizeDeps.exclude`.
624
+ *
625
+ * @default true for dev, false for build
558
626
  */
559
627
  prebundleSvelteLibraries?: boolean;
560
628
 
@@ -656,6 +724,13 @@ export interface ExperimentalOptions {
656
724
  *
657
725
  */
658
726
  sendWarningsToBrowser?: boolean;
727
+
728
+ /**
729
+ * disable svelte compile statistics
730
+ *
731
+ * @default false
732
+ */
733
+ disableCompileStats?: 'dev' | 'build' | boolean;
659
734
  }
660
735
 
661
736
  export interface InspectorOptions {
@@ -742,6 +817,7 @@ export interface PreResolvedOptions extends Options {
742
817
  export interface ResolvedOptions extends PreResolvedOptions {
743
818
  isProduction: boolean;
744
819
  server?: ViteDevServer;
820
+ stats?: VitePluginSvelteStats;
745
821
  }
746
822
 
747
823
  export type {
@@ -1,25 +1,24 @@
1
1
  import path from 'path';
2
- import { builtinModules, createRequire } from 'module';
3
- import { is_common_without_svelte_field, resolveDependencyData } from './dependencies';
2
+ import { builtinModules } from 'module';
3
+ import { resolveDependencyData, isCommonDepWithoutSvelteField } from './dependencies';
4
4
  import { VitePluginSvelteCache } from './vite-plugin-svelte-cache';
5
5
 
6
- export function resolveViaPackageJsonSvelte(
6
+ export async function resolveViaPackageJsonSvelte(
7
7
  importee: string,
8
8
  importer: string | undefined,
9
9
  cache: VitePluginSvelteCache
10
- ): string | void {
10
+ ): Promise<string | void> {
11
11
  if (
12
12
  importer &&
13
13
  isBareImport(importee) &&
14
14
  !isNodeInternal(importee) &&
15
- !is_common_without_svelte_field(importee)
15
+ !isCommonDepWithoutSvelteField(importee)
16
16
  ) {
17
17
  const cached = cache.getResolvedSvelteField(importee, importer);
18
18
  if (cached) {
19
19
  return cached;
20
20
  }
21
- const localRequire = createRequire(importer);
22
- const pkgData = resolveDependencyData(importee, localRequire);
21
+ const pkgData = await resolveDependencyData(importee, importer);
23
22
  if (pkgData) {
24
23
  const { pkg, dir } = pkgData;
25
24
  if (pkg.svelte) {
@@ -0,0 +1,37 @@
1
+ import { VERSION } from 'svelte/compiler';
2
+ const svelteVersion = parseVersion(VERSION);
3
+
4
+ export function parseVersion(version: string): number[] {
5
+ const segments = version.split('.', 3).map((s) => parseInt(s, 10));
6
+ while (segments.length < 3) {
7
+ segments.push(0);
8
+ }
9
+ return segments;
10
+ }
11
+
12
+ /**
13
+ * compare version with current svelte, only takes major.minor.patch into account.
14
+ * If you don't pass all three, values will be filled with 0, ie `3` is equal to `3.0.0`
15
+ * @param version
16
+ * @returns 1 if passed version is larger than current, 0 if it is equal and -1 if it is lower
17
+ */
18
+ export function compareToSvelte(version: string): 1 | 0 | -1 {
19
+ const parsedVersion = parseVersion(version);
20
+ for (let i = 0; i < svelteVersion.length; i++) {
21
+ const a = parsedVersion[i];
22
+ const b = svelteVersion[i];
23
+ if (a === b) {
24
+ continue;
25
+ } else if (a > b) {
26
+ return 1;
27
+ } else {
28
+ return -1;
29
+ }
30
+ }
31
+ return 0;
32
+ }
33
+
34
+ export function atLeastSvelte(version: string) {
35
+ const result = compareToSvelte(version) <= 0;
36
+ return result;
37
+ }