From 986a561ba7507a75f826020e66a92f5b7c5531e5 Mon Sep 17 00:00:00 2001 From: bluwy Date: Wed, 26 Oct 2022 23:45:36 +0800 Subject: [PATCH 01/14] refactor: use vitefu to handle svelte libraries --- .changeset/loud-cameras-double.md | 5 + packages/vite-plugin-svelte/package.json | 3 +- packages/vite-plugin-svelte/src/index.ts | 4 +- .../src/utils/__tests__/dependencies.spec.ts | 43 ---- .../src/utils/dependencies.ts | 190 ++---------------- .../vite-plugin-svelte/src/utils/options.ts | 142 +++++-------- .../vite-plugin-svelte/src/utils/resolve.ts | 13 +- pnpm-lock.yaml | 54 ++--- 8 files changed, 105 insertions(+), 349 deletions(-) create mode 100644 .changeset/loud-cameras-double.md delete mode 100644 packages/vite-plugin-svelte/src/utils/__tests__/dependencies.spec.ts diff --git a/.changeset/loud-cameras-double.md b/.changeset/loud-cameras-double.md new file mode 100644 index 000000000..99c960172 --- /dev/null +++ b/.changeset/loud-cameras-double.md @@ -0,0 +1,5 @@ +--- +'@sveltejs/vite-plugin-svelte': patch +--- + +Refactor Svelte libraries config handling diff --git a/packages/vite-plugin-svelte/package.json b/packages/vite-plugin-svelte/package.json index 9433cf541..695b87533 100644 --- a/packages/vite-plugin-svelte/package.json +++ b/packages/vite-plugin-svelte/package.json @@ -50,7 +50,8 @@ "deepmerge": "^4.2.2", "kleur": "^4.1.5", "magic-string": "^0.26.7", - "svelte-hmr": "^0.15.0" + "svelte-hmr": "^0.15.0", + "vitefu": "^0.0.1" }, "peerDependencies": { "diff-match-patch": "^1.0.5", diff --git a/packages/vite-plugin-svelte/src/index.ts b/packages/vite-plugin-svelte/src/index.ts index 22dcc4803..9ad1bf875 100644 --- a/packages/vite-plugin-svelte/src/index.ts +++ b/packages/vite-plugin-svelte/src/index.ts @@ -68,7 +68,7 @@ export function svelte(inlineOptions?: Partial): Plugin[] { // @ts-expect-error temporarily lend the options variable until fixed in configResolved options = await preResolveOptions(inlineOptions, config, configEnv); // extra vite config - const extraViteConfig = buildExtraViteConfig(options, config); + const extraViteConfig = await buildExtraViteConfig(options, config); log.debug('additional vite config', extraViteConfig); return extraViteConfig; }, @@ -155,7 +155,7 @@ export function svelte(inlineOptions?: Partial): Plugin[] { return resolvedSvelteSSR; } try { - const resolved = resolveViaPackageJsonSvelte(importee, importer, cache); + const resolved = await resolveViaPackageJsonSvelte(importee, importer, cache); if (resolved) { log.debug( `resolveId resolved ${resolved} via package.json svelte field of ${importee}` diff --git a/packages/vite-plugin-svelte/src/utils/__tests__/dependencies.spec.ts b/packages/vite-plugin-svelte/src/utils/__tests__/dependencies.spec.ts deleted file mode 100644 index baca99176..000000000 --- a/packages/vite-plugin-svelte/src/utils/__tests__/dependencies.spec.ts +++ /dev/null @@ -1,43 +0,0 @@ -import { describe, it, expect } from 'vitest'; -import { findRootSvelteDependencies, needsOptimization } from '../dependencies'; -import * as path from 'path'; -import { createRequire } from 'module'; -import { fileURLToPath } from 'url'; -const __dir = path.dirname(fileURLToPath(import.meta.url)); -const e2eTestRoot = path.resolve(__dir, '../../../../../packages/e2e-tests'); - -describe('dependencies', () => { - describe('findRootSvelteDependencies', () => { - it('should find svelte dependencies in packages/e2e-test/hmr', () => { - const deps = findRootSvelteDependencies(path.resolve('packages/e2e-tests/hmr')); - expect(deps).toHaveLength(1); - expect(deps[0].name).toBe('e2e-test-dep-svelte-simple'); - expect(deps[0].path).toEqual([]); - }); - it('should find nested svelte dependencies in packages/e2e-test/package-json-svelte-field', () => { - const deps = findRootSvelteDependencies(path.join(e2eTestRoot, 'package-json-svelte-field')); - expect(deps).toHaveLength(3); - const hybrid = deps.find((dep) => dep.name === 'e2e-test-dep-svelte-hybrid'); - expect(hybrid).toBeTruthy(); - expect(hybrid.path).toHaveLength(0); - const nested = deps.find((dep) => dep.name === 'e2e-test-dep-svelte-nested'); - expect(nested).toBeTruthy(); - expect(nested.path).toHaveLength(0); - const simple = deps.find((dep) => dep.name === 'e2e-test-dep-svelte-simple'); - expect(simple).toBeTruthy(); - expect(simple.path).toHaveLength(1); - expect(simple.path[0]).toBe('e2e-test-dep-svelte-nested'); - }); - }); - describe('needsOptimization', () => { - it('should optimize cjs deps only', () => { - const testDepsPath = path.join(e2eTestRoot, 'dependencies/package.json'); - const localRequire = createRequire(testDepsPath); - expect(needsOptimization('e2e-test-dep-cjs-and-esm', localRequire)).toBe(false); - expect(needsOptimization('e2e-test-dep-cjs-only', localRequire)).toBe(true); - expect(needsOptimization('e2e-test-dep-esm-only', localRequire)).toBe(false); - expect(needsOptimization('e2e-test-dep-index-only', localRequire)).toBe(true); - expect(needsOptimization('e2e-test-dep-types-only', localRequire)).toBe(false); - }); - }); -}); diff --git a/packages/vite-plugin-svelte/src/utils/dependencies.ts b/packages/vite-plugin-svelte/src/utils/dependencies.ts index 9061d4442..428c8c6a5 100644 --- a/packages/vite-plugin-svelte/src/utils/dependencies.ts +++ b/packages/vite-plugin-svelte/src/utils/dependencies.ts @@ -1,130 +1,29 @@ -import { log } from './log'; import path from 'path'; -import fs from 'fs'; -import { createRequire } from 'module'; +import fs from 'fs/promises'; +// eslint-disable-next-line node/no-missing-import +import { findDepPkgJsonPath } from 'vitefu'; -export function findRootSvelteDependencies(root: string, cwdFallback = true): SvelteDependency[] { - log.debug(`findSvelteDependencies: searching svelte dependencies in ${root}`); - const pkgFile = path.join(root, 'package.json'); - if (!fs.existsSync(pkgFile)) { - if (cwdFallback) { - const cwd = process.cwd(); - if (root !== cwd) { - log.debug(`no package.json found in vite root ${root}`); - return findRootSvelteDependencies(cwd, false); - } - } - log.warn(`no package.json found, findRootSvelteDependencies failed`); - return []; - } - - const pkg = parsePkg(root); - if (!pkg) { - return []; - } - - const deps = [ - ...Object.keys(pkg.dependencies || {}), - ...Object.keys(pkg.devDependencies || {}) - ].filter((dep) => !is_common_without_svelte_field(dep)); - - return getSvelteDependencies(deps, root); -} - -function getSvelteDependencies( - deps: string[], - pkgDir: string, - path: string[] = [] -): SvelteDependency[] { - const result = []; - const localRequire = createRequire(`${pkgDir}/package.json`); - const resolvedDeps = deps - .map((dep) => resolveDependencyData(dep, localRequire)) - .filter(Boolean) as DependencyData[]; - for (const { pkg, dir } of resolvedDeps) { - const type = getSvelteDependencyType(pkg); - if (!type) continue; - result.push({ name: pkg.name, type, pkg, dir, path }); - // continue crawling for component libraries so we can optimize them, js libraries are fine - if (type === 'component-library' && pkg.dependencies) { - let dependencyNames = Object.keys(pkg.dependencies); - const circular = dependencyNames.filter((name) => path.includes(name)); - if (circular.length > 0) { - log.warn.enabled && - log.warn( - `skipping circular svelte dependencies in automated vite optimizeDeps handling`, - circular.map((x) => path.concat(x).join('>')) - ); - dependencyNames = dependencyNames.filter((name) => !path.includes(name)); - } - if (path.length === 3) { - log.debug.once(`encountered deep svelte dependency tree: ${path.join('>')}`); - } - result.push(...getSvelteDependencies(dependencyNames, dir, path.concat(pkg.name))); - } - } - return result; +interface DependencyData { + dir: string; + pkg: Record; } -export function resolveDependencyData( +export async function resolveDependencyData( dep: string, - localRequire: NodeRequire -): DependencyData | void { - try { - const pkgJson = `${dep}/package.json`; - const pkg = localRequire(pkgJson); - const dir = path.dirname(localRequire.resolve(pkgJson)); - return { dir, pkg }; - } catch (e) { - log.debug.once(`dependency ${dep} does not export package.json`, e); - // walk up from default export until we find package.json with name=dep - try { - let dir = path.dirname(localRequire.resolve(dep)); - while (dir) { - const pkg = parsePkg(dir, true); - if (pkg && pkg.name === dep) { - return { dir, pkg }; - } - const parent = path.dirname(dir); - if (parent === dir) { - break; - } - dir = parent; - } - } catch (e) { - log.debug.once(`error while trying to find package.json of ${dep}`, e); - } - } - log.debug.once(`failed to resolve ${dep}`); -} - -function parsePkg(dir: string, silent = false): Pkg | void { - const pkgFile = path.join(dir, 'package.json'); + parent: string +): Promise { + const depDataPath = await findDepPkgJsonPath(dep, parent); + if (!depDataPath) return undefined; try { - return JSON.parse(fs.readFileSync(pkgFile, 'utf-8')); - } catch (e) { - !silent && log.warn.enabled && log.warn(`failed to parse ${pkgFile}`, e); - } -} - -function getSvelteDependencyType(pkg: Pkg): SvelteDependencyType | undefined { - if (isSvelteComponentLib(pkg)) { - return 'component-library'; - } else if (isSvelteLib(pkg)) { - return 'js-library'; - } else { + return { + dir: path.dirname(depDataPath), + pkg: JSON.parse(await fs.readFile(depDataPath, 'utf-8')) + }; + } catch { return undefined; } } -function isSvelteComponentLib(pkg: Pkg) { - return !!pkg.svelte; -} - -function isSvelteLib(pkg: Pkg) { - return !!pkg.dependencies?.svelte || !!pkg.peerDependencies?.svelte; -} - const COMMON_DEPENDENCIES_WITHOUT_SVELTE_FIELD = [ '@lukeed/uuid', '@playwright/test', @@ -173,7 +72,7 @@ const COMMON_PREFIXES_WITHOUT_SVELTE_FIELD = [ * @param dependency {string} * @returns {boolean} true if it is a dependency without a svelte field */ -export function is_common_without_svelte_field(dependency: string): boolean { +export function isCommonDepWithoutSvelteField(dependency: string): boolean { return ( COMMON_DEPENDENCIES_WITHOUT_SVELTE_FIELD.includes(dependency) || COMMON_PREFIXES_WITHOUT_SVELTE_FIELD.some( @@ -184,58 +83,3 @@ export function is_common_without_svelte_field(dependency: string): boolean { ) ); } - -export function needsOptimization(dep: string, localRequire: NodeRequire): boolean { - const depData = resolveDependencyData(dep, localRequire); - if (!depData) return false; - const pkg = depData.pkg; - // only optimize if is cjs, using the below as heuristic - // see https://github.com/sveltejs/vite-plugin-svelte/issues/162 - const hasEsmFields = pkg.module || pkg.exports; - if (hasEsmFields) return false; - if (pkg.main) { - // ensure entry is js so vite can prebundle it - // see https://github.com/sveltejs/vite-plugin-svelte/issues/233 - const entryExt = path.extname(pkg.main); - return !entryExt || entryExt === '.js' || entryExt === '.cjs'; - } else { - // check if has implicit index.js entrypoint - // https://github.com/sveltejs/vite-plugin-svelte/issues/281 - try { - localRequire.resolve(`${dep}/index.js`); - return true; - } catch { - return false; - } - } -} - -interface DependencyData { - dir: string; - pkg: Pkg; -} - -export interface SvelteDependency { - name: string; - type: SvelteDependencyType; - dir: string; - pkg: Pkg; - path: string[]; -} - -// component-library => exports svelte components -// js-library => only uses svelte api, no components -export type SvelteDependencyType = 'component-library' | 'js-library'; - -export interface Pkg { - name: string; - svelte?: string; - dependencies?: DependencyList; - devDependencies?: DependencyList; - peerDependencies?: DependencyList; - [key: string]: any; -} - -export interface DependencyList { - [key: string]: string; -} diff --git a/packages/vite-plugin-svelte/src/utils/options.ts b/packages/vite-plugin-svelte/src/utils/options.ts index 1cad44156..0ed492142 100644 --- a/packages/vite-plugin-svelte/src/utils/options.ts +++ b/packages/vite-plugin-svelte/src/utils/options.ts @@ -21,11 +21,12 @@ import type { } from 'svelte/types/compiler/preprocess'; import path from 'path'; -import { findRootSvelteDependencies, needsOptimization, SvelteDependency } from './dependencies'; -import { createRequire } from 'module'; import { esbuildSveltePlugin, facadeEsbuildSveltePluginName } from './esbuild'; import { addExtraPreprocessors } from './preprocess'; import deepmerge from 'deepmerge'; +// eslint-disable-next-line node/no-missing-import +import { crawlFrameworkPkgs } from 'vitefu'; +import { isCommonDepWithoutSvelteField } from './dependencies'; const allowedPluginOptions = new Set([ 'include', @@ -306,12 +307,10 @@ function resolveViteRoot(viteConfig: UserConfig): string | undefined { return normalizePath(viteConfig.root ? path.resolve(viteConfig.root) : process.cwd()); } -export function buildExtraViteConfig( +export async function buildExtraViteConfig( options: PreResolvedOptions, config: UserConfig -): Partial { - // extra handling for svelte dependencies in the project - const svelteDeps = findRootSvelteDependencies(options.root); +): Promise> { const extraViteConfig: Partial = { resolve: { mainFields: [...SVELTE_RESOLVE_MAIN_FIELDS], @@ -323,12 +322,29 @@ export function buildExtraViteConfig( // knownJsSrcExtensions: options.extensions }; - extraViteConfig.optimizeDeps = buildOptimizeDepsForSvelte( - svelteDeps, - options, - config.optimizeDeps - ); + // extra handling for svelte dependencies in the project + const depsConfig = await crawlFrameworkPkgs({ + root: options.root, + isBuild: options.isBuild, + viteUserConfig: config, + isFrameworkPkgByJson(pkgJson) { + return !!pkgJson.svelte; + }, + isSemiFrameworkPkgByJson(pkgJson) { + return !!pkgJson.dependencies?.svelte || !!pkgJson.peerDependencies?.svelte; + }, + isFrameworkPkgByName(pkgName) { + const isNotSveltePackage = isCommonDepWithoutSvelteField(pkgName); + if (isNotSveltePackage) { + return false; + } else { + return undefined; + } + } + }); + // optimize deps + extraViteConfig.optimizeDeps = buildOptimizeDepsForSvelte(config); if (options.prebundleSvelteLibraries) { extraViteConfig.optimizeDeps = { ...extraViteConfig.optimizeDeps, @@ -342,10 +358,30 @@ export function buildExtraViteConfig( plugins: [{ name: facadeEsbuildSveltePluginName, setup: () => {} }] } }; + } else { + if (options.disableDependencyReinclusion !== true) { + const disabledReinclusions = options.disableDependencyReinclusion || []; + if (disabledReinclusions.length > 0) { + log.debug(`not reincluding transitive dependencies of`, disabledReinclusions); + } + const transitiveDepsToInclude = depsConfig.optimizeDeps.include.filter((dep) => + disabledReinclusions.every((disabled) => !dep.includes(disabled)) + ); + log.debug( + `reincluding transitive dependencies of excluded svelte dependencies`, + transitiveDepsToInclude + ); + depsConfig.optimizeDeps.include?.push(...transitiveDepsToInclude); + } + extraViteConfig.optimizeDeps.include?.push(...depsConfig.optimizeDeps.include); + extraViteConfig.optimizeDeps.exclude?.push(...depsConfig.optimizeDeps.exclude); } - // @ts-ignore - extraViteConfig.ssr = buildSSROptionsForSvelte(svelteDeps, options, config, extraViteConfig); + // ssr config + extraViteConfig.ssr = buildSSROptionsForSvelte(config); + // @ts-expect-error `noExternal` is 100% an array + extraViteConfig.ssr?.noExternal?.push(...depsConfig.ssr.noExternal); + extraViteConfig.ssr?.external?.push(...depsConfig.ssr.external); // enable hmrPartialAccept if not explicitly disabled if ( @@ -361,21 +397,18 @@ export function buildExtraViteConfig( return extraViteConfig; } -function buildOptimizeDepsForSvelte( - svelteDeps: SvelteDependency[], - options: PreResolvedOptions, - optimizeDeps?: DepOptimizationOptions -): DepOptimizationOptions { +function buildOptimizeDepsForSvelte(config: UserConfig): 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 isIncluded = (dep: string) => + include.includes(dep) || config.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: string) => dep === id || id.startsWith(`${dep}/`)) + config.optimizeDeps?.exclude?.some((id: string) => dep === id || id.startsWith(`${dep}/`)) ); }; if (!isExcluded('svelte')) { @@ -387,82 +420,17 @@ function buildOptimizeDepsForSvelte( } else { log.debug('"svelte" is excluded in optimizeDeps.exclude, skipped adding it to include.'); } - - // If we prebundle svelte libraries, we can skip the whole prebundling dance below - if (options.prebundleSvelteLibraries) { - return { include, exclude }; - } - - // only svelte component libraries needs to be processed for optimizeDeps, js libraries work fine - svelteDeps = svelteDeps.filter((dep) => dep.type === 'component-library'); - - 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 { +function buildSSROptionsForSvelte(config: UserConfig): any { const noExternal: (string | RegExp)[] = []; - // add svelte to ssr.noExternal unless it is present in ssr.external // so we can resolve it with svelte/ssr if (!config.ssr?.external?.includes('svelte')) { noExternal.push('svelte', /^svelte\//); } - - // add svelte dependencies to ssr.noExternal unless present in ssr.external - noExternal.push( - ...Array.from(new Set(svelteDeps.map((s) => s.name))).filter( - (x) => !config.ssr?.external?.includes(x) - ) - ); - const ssr = { - noExternal, - external: [] as string[] - }; - - if (options.isServe) { - // during dev, we have to externalize transitive dependencies, see https://github.com/sveltejs/vite-plugin-svelte/issues/281 - ssr.external = Array.from( - new Set(svelteDeps.flatMap((dep) => Object.keys(dep.pkg.dependencies || {}))) - ).filter( - (dep) => - !ssr.noExternal.includes(dep) && - // TODO noExternal can be something different than a string array - //!config.ssr?.noExternal?.includes(dep) && - !config.ssr?.external?.includes(dep) - ); - } - - return ssr; + return { noExternal, external: [] }; } export function patchResolvedViteConfig(viteConfig: ResolvedConfig, options: ResolvedOptions) { diff --git a/packages/vite-plugin-svelte/src/utils/resolve.ts b/packages/vite-plugin-svelte/src/utils/resolve.ts index 2e03e2297..8fdb55390 100644 --- a/packages/vite-plugin-svelte/src/utils/resolve.ts +++ b/packages/vite-plugin-svelte/src/utils/resolve.ts @@ -1,25 +1,24 @@ import path from 'path'; -import { builtinModules, createRequire } from 'module'; -import { is_common_without_svelte_field, resolveDependencyData } from './dependencies'; +import { builtinModules } from 'module'; +import { resolveDependencyData, isCommonDepWithoutSvelteField } from './dependencies'; import { VitePluginSvelteCache } from './vite-plugin-svelte-cache'; -export function resolveViaPackageJsonSvelte( +export async function resolveViaPackageJsonSvelte( importee: string, importer: string | undefined, cache: VitePluginSvelteCache -): string | void { +): Promise { if ( importer && isBareImport(importee) && !isNodeInternal(importee) && - !is_common_without_svelte_field(importee) + !isCommonDepWithoutSvelteField(importee) ) { const cached = cache.getResolvedSvelteField(importee, importer); if (cached) { return cached; } - const localRequire = createRequire(importer); - const pkgData = resolveDependencyData(importee, localRequire); + const pkgData = await resolveDependencyData(importee, importer); if (pkgData) { const { pkg, dir } = pkgData; if (pkg.svelte) { diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 90ae7bf2e..478894f5a 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -473,12 +473,14 @@ importers: svelte-hmr: ^0.15.0 tsup: ^6.3.0 vite: ^3.1.8 + vitefu: ^0.0.1 dependencies: debug: 4.3.4 deepmerge: 4.2.2 kleur: 4.1.5 magic-string: 0.26.7 svelte-hmr: 0.15.0_svelte@3.52.0 + vitefu: 0.0.1_vite@3.1.8 devDependencies: '@types/debug': 4.1.7 '@types/diff-match-patch': 1.0.32 @@ -729,7 +731,6 @@ packages: cpu: [arm] os: [android] requiresBuild: true - dev: true optional: true /@esbuild/linux-loong64/0.15.12: @@ -738,7 +739,6 @@ packages: cpu: [loong64] os: [linux] requiresBuild: true - dev: true optional: true /@eslint/eslintrc/1.3.3: @@ -2185,7 +2185,6 @@ packages: cpu: [x64] os: [android] requiresBuild: true - dev: true optional: true /esbuild-android-arm64/0.15.12: @@ -2194,7 +2193,6 @@ packages: cpu: [arm64] os: [android] requiresBuild: true - dev: true optional: true /esbuild-darwin-64/0.15.12: @@ -2203,7 +2201,6 @@ packages: cpu: [x64] os: [darwin] requiresBuild: true - dev: true optional: true /esbuild-darwin-arm64/0.15.12: @@ -2212,7 +2209,6 @@ packages: cpu: [arm64] os: [darwin] requiresBuild: true - dev: true optional: true /esbuild-freebsd-64/0.15.12: @@ -2221,7 +2217,6 @@ packages: cpu: [x64] os: [freebsd] requiresBuild: true - dev: true optional: true /esbuild-freebsd-arm64/0.15.12: @@ -2230,7 +2225,6 @@ packages: cpu: [arm64] os: [freebsd] requiresBuild: true - dev: true optional: true /esbuild-linux-32/0.15.12: @@ -2239,7 +2233,6 @@ packages: cpu: [ia32] os: [linux] requiresBuild: true - dev: true optional: true /esbuild-linux-64/0.15.12: @@ -2248,7 +2241,6 @@ packages: cpu: [x64] os: [linux] requiresBuild: true - dev: true optional: true /esbuild-linux-arm/0.15.12: @@ -2257,7 +2249,6 @@ packages: cpu: [arm] os: [linux] requiresBuild: true - dev: true optional: true /esbuild-linux-arm64/0.15.12: @@ -2266,7 +2257,6 @@ packages: cpu: [arm64] os: [linux] requiresBuild: true - dev: true optional: true /esbuild-linux-mips64le/0.15.12: @@ -2275,7 +2265,6 @@ packages: cpu: [mips64el] os: [linux] requiresBuild: true - dev: true optional: true /esbuild-linux-ppc64le/0.15.12: @@ -2284,7 +2273,6 @@ packages: cpu: [ppc64] os: [linux] requiresBuild: true - dev: true optional: true /esbuild-linux-riscv64/0.15.12: @@ -2293,7 +2281,6 @@ packages: cpu: [riscv64] os: [linux] requiresBuild: true - dev: true optional: true /esbuild-linux-s390x/0.15.12: @@ -2302,7 +2289,6 @@ packages: cpu: [s390x] os: [linux] requiresBuild: true - dev: true optional: true /esbuild-netbsd-64/0.15.12: @@ -2311,7 +2297,6 @@ packages: cpu: [x64] os: [netbsd] requiresBuild: true - dev: true optional: true /esbuild-openbsd-64/0.15.12: @@ -2320,7 +2305,6 @@ packages: cpu: [x64] os: [openbsd] requiresBuild: true - dev: true optional: true /esbuild-sunos-64/0.15.12: @@ -2329,7 +2313,6 @@ packages: cpu: [x64] os: [sunos] requiresBuild: true - dev: true optional: true /esbuild-windows-32/0.15.12: @@ -2338,7 +2321,6 @@ packages: cpu: [ia32] os: [win32] requiresBuild: true - dev: true optional: true /esbuild-windows-64/0.15.12: @@ -2347,7 +2329,6 @@ packages: cpu: [x64] os: [win32] requiresBuild: true - dev: true optional: true /esbuild-windows-arm64/0.15.12: @@ -2356,7 +2337,6 @@ packages: cpu: [arm64] os: [win32] requiresBuild: true - dev: true optional: true /esbuild/0.15.12: @@ -2387,7 +2367,6 @@ packages: esbuild-windows-32: 0.15.12 esbuild-windows-64: 0.15.12 esbuild-windows-arm64: 0.15.12 - dev: true /escalade/3.1.1: resolution: {integrity: sha512-k0er2gUkLf8O0zKJiAhmkTnJlTvINGv7ygDNPbeIsX/TJjGJZHuh9B2UxbsaEkmlEo9MfhrSzmhIlhRlI2GXnw==} @@ -2900,12 +2879,10 @@ packages: engines: {node: ^8.16.0 || ^10.6.0 || >=11.0.0} os: [darwin] requiresBuild: true - dev: true optional: true /function-bind/1.1.1: resolution: {integrity: sha512-yIovAzMX49sF8Yl58fSCWJ5svSLuaibPxXQJFLmBObTuCr0Mf1KiPopGM9NiFjiYBCbfaa2Fh6breQ6ANVTI0A==} - dev: true /function.prototype.name/1.1.5: resolution: {integrity: sha512-uN7m/BzVKQnCUF/iW8jYea67v++2u7m5UgENbHRtdDVclOUP+FMPlCNdmk0h/ysGyo2tavMJEDqJAkJdRa1vMA==} @@ -3094,7 +3071,6 @@ packages: engines: {node: '>= 0.4.0'} dependencies: function-bind: 1.1.1 - dev: true /hosted-git-info/2.8.9: resolution: {integrity: sha512-mxIDAb9Lsm6DoOJ7xH+5+X4y1LU/4Hi50L9C5sIswK3JzULS4bwk1FvjdBgvYR4bzT4tuUQiC15FE2f5HbLvYw==} @@ -3174,6 +3150,10 @@ packages: resolve-from: 4.0.0 dev: true + /import-meta-resolve/2.1.0: + resolution: {integrity: sha512-yG9pxkWJVTy4cmRsNWE3ztFdtFuYIV8G4N+cbCkO8b+qngkLyIUhxQFuZ0qJm67+0nUOxjMPT7nfksPKza1v2g==} + dev: false + /imurmurhash/0.1.4: resolution: {integrity: sha512-JmXMZ6wuvDmLiHEml9ykzqO6lwFbof0GG4IkcGaENdCRDDmMVnny7s5HsIgHCbaq0w2MyPhDqkhTUgS2LU2PHA==} engines: {node: '>=0.8.19'} @@ -3277,7 +3257,6 @@ packages: resolution: {integrity: sha512-Erxj2n/LDAZ7H8WNJXd9tw38GYM3dv8rk8Zcs+jJuxYTW7sozH+SS8NtrSjVL1/vpLvWi1hxy96IzjJ3EHTJJg==} dependencies: has: 1.0.3 - dev: true /is-date-object/1.0.5: resolution: {integrity: sha512-9YQaSxsAiSwcvS33MBk3wTCVnWK+HhF8VZR2jRxehM16QcVOdHqPn4VPHmRK4lSr38n9JriurInLcP90xsYNfQ==} @@ -3876,7 +3855,6 @@ packages: resolution: {integrity: sha512-MqBkQh/OHTS2egovRtLk45wEyNXwF+cokD+1YPf9u5VfJiRdAiRwB2froX5Co9Rh20xs4siNPm8naNotSD6RBw==} engines: {node: ^10 || ^12 || ^13.7 || ^14 || >=15.0.1} hasBin: true - dev: true /natural-compare/1.4.0: resolution: {integrity: sha512-OWND8ei3VtNC9h7V60qff3SVobHr996CTwgxubgyQYEpg290h9J0buyECNNJexkFm5sOajh5G116RYA1c8ZMSw==} @@ -4189,7 +4167,6 @@ packages: /path-parse/1.0.7: resolution: {integrity: sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw==} - dev: true /path-to-regexp/0.1.7: resolution: {integrity: sha512-5DFkuoqlv1uYQKxy8omFBeJPQcdoE07Kv2sferDCrAq1ohOU+MSDswDIbnx3YAM60qIOnYa53wBhXW0EbMonrQ==} @@ -4213,7 +4190,6 @@ packages: /picocolors/1.0.0: resolution: {integrity: sha512-1fygroTLlHu66zi26VoTDv8yRgm0Fccecssto+MhsZ0D/DGW2sm8E8AjW7NU5VVTRt5GxbeZ5qBuJr+HyLYkjQ==} - dev: true /picomatch/2.3.1: resolution: {integrity: sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA==} @@ -4304,7 +4280,6 @@ packages: nanoid: 3.3.4 picocolors: 1.0.0 source-map-js: 1.0.2 - dev: true /preferred-pm/3.0.3: resolution: {integrity: sha512-+wZgbxNES/KlJs9q40F/1sfOd/j7f1O9JaHcW5Dsn3aUUOZg3L2bjpVUcKV2jvtElYfoTuQiNeMfQJ4kwUAhCQ==} @@ -4512,7 +4487,6 @@ packages: is-core-module: 2.10.0 path-parse: 1.0.7 supports-preserve-symlinks-flag: 1.0.0 - dev: true /restore-cursor/3.1.0: resolution: {integrity: sha512-l+sSefzHpj5qimhFSE5a8nufZYAM3sBSVMAPtYkmC+4EH2anSGaEMXSD0izRQbu9nfyQ9y5JrVmp7E8oZrUjvA==} @@ -4557,7 +4531,6 @@ packages: hasBin: true optionalDependencies: fsevents: 2.3.2 - dev: true /rollup/2.79.1: resolution: {integrity: sha512-uKxbd0IhMZOhjAiD5oAFp7BqvkA4Dv47qpOCtaNvng4HBwdbWtdOh8f5nZNuk2rp51PMGk3bzfWu5oayNEuYnw==} @@ -4790,7 +4763,6 @@ packages: /source-map-js/1.0.2: resolution: {integrity: sha512-R0XvVJ9WusLiqTCEiGCmICCMplcCkIwwR11mOSD9CR5u+IXYdiseeEuXCVAjS54zqwkLcPNnmU4OeJ6tUrWhDw==} engines: {node: '>=0.10.0'} - dev: true /source-map/0.7.3: resolution: {integrity: sha512-CkCj6giN3S+n9qrYiBTX5gystlENnRW5jZeNLHpe6aue+SrHcG5VYwujhW9s4dY31mEGsxBDrHR6oI69fTXsaQ==} @@ -5000,7 +4972,6 @@ packages: /supports-preserve-symlinks-flag/1.0.0: resolution: {integrity: sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w==} engines: {node: '>= 0.4'} - dev: true /svelte-check/2.9.2_svelte@3.52.0: resolution: {integrity: sha512-DRi8HhnCiqiGR2YF9ervPGvtoYrheE09cXieCTEqeTPOTJzfoa54Py8rovIBv4bH4n5HgZYIyTQ3DDLHQLl2uQ==} @@ -5606,7 +5577,6 @@ packages: rollup: 2.78.1 optionalDependencies: fsevents: 2.3.2 - dev: true /vite/3.1.8_sass@1.55.0: resolution: {integrity: sha512-m7jJe3nufUbuOfotkntGFupinL/fmuTNuQmiVE7cH2IZMuf4UbfbGYMUT3jVWgGYuRVLY9j8NnrRqgw5rr5QTg==} @@ -5665,6 +5635,18 @@ packages: fsevents: 2.3.2 dev: true + /vitefu/0.0.1_vite@3.1.8: + resolution: {integrity: sha512-lOPcUgjTPi7hs1nAIgv8wOkIlMiNMzuWe8Ts7mM9IsH0OZkNjv24CZ0XX0ET/nS6CP8+Lij8j2ZpiLe7bVKVVQ==} + peerDependencies: + vite: ^3.0.0 || ^3.1.0 + peerDependenciesMeta: + vite: + optional: true + dependencies: + import-meta-resolve: 2.1.0 + vite: 3.1.8 + dev: false + /vitest/0.24.3: resolution: {integrity: sha512-aM0auuPPgMSstWvr851hB74g/LKaKBzSxcG3da7ejfZbx08Y21JpZmbmDYrMTCGhVZKqTGwzcnLMwyfz2WzkhQ==} engines: {node: '>=v14.16.0'} From ed901cbfd836fa977d21f6e0482bb159754d1a4a Mon Sep 17 00:00:00 2001 From: bluwy Date: Thu, 27 Oct 2022 01:51:26 +0800 Subject: [PATCH 02/14] chore: upgrade vitefu --- packages/vite-plugin-svelte/package.json | 2 +- pnpm-lock.yaml | 8 ++++---- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/packages/vite-plugin-svelte/package.json b/packages/vite-plugin-svelte/package.json index 695b87533..04c01b565 100644 --- a/packages/vite-plugin-svelte/package.json +++ b/packages/vite-plugin-svelte/package.json @@ -51,7 +51,7 @@ "kleur": "^4.1.5", "magic-string": "^0.26.7", "svelte-hmr": "^0.15.0", - "vitefu": "^0.0.1" + "vitefu": "^0.1.0" }, "peerDependencies": { "diff-match-patch": "^1.0.5", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 478894f5a..a23d50777 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -473,14 +473,14 @@ importers: svelte-hmr: ^0.15.0 tsup: ^6.3.0 vite: ^3.1.8 - vitefu: ^0.0.1 + vitefu: ^0.1.0 dependencies: debug: 4.3.4 deepmerge: 4.2.2 kleur: 4.1.5 magic-string: 0.26.7 svelte-hmr: 0.15.0_svelte@3.52.0 - vitefu: 0.0.1_vite@3.1.8 + vitefu: 0.1.0_vite@3.1.8 devDependencies: '@types/debug': 4.1.7 '@types/diff-match-patch': 1.0.32 @@ -5635,8 +5635,8 @@ packages: fsevents: 2.3.2 dev: true - /vitefu/0.0.1_vite@3.1.8: - resolution: {integrity: sha512-lOPcUgjTPi7hs1nAIgv8wOkIlMiNMzuWe8Ts7mM9IsH0OZkNjv24CZ0XX0ET/nS6CP8+Lij8j2ZpiLe7bVKVVQ==} + /vitefu/0.1.0_vite@3.1.8: + resolution: {integrity: sha512-5MQSHP9yr0HIve8q4XNb7QXfO1P4tzZDZP99qH0FM5ClcwYddeGXRDQ4TQYRUeXLjZ+vLecirHtGNpwFFUF7sw==} peerDependencies: vite: ^3.0.0 || ^3.1.0 peerDependenciesMeta: From 6de395d0d2c328ff56ebcf67b9f3b66bb653c9eb Mon Sep 17 00:00:00 2001 From: bluwy Date: Thu, 27 Oct 2022 15:17:14 +0800 Subject: [PATCH 03/14] chore: add debug log --- packages/vite-plugin-svelte/src/utils/options.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/packages/vite-plugin-svelte/src/utils/options.ts b/packages/vite-plugin-svelte/src/utils/options.ts index 0ed492142..ad8a8f058 100644 --- a/packages/vite-plugin-svelte/src/utils/options.ts +++ b/packages/vite-plugin-svelte/src/utils/options.ts @@ -343,6 +343,8 @@ export async function buildExtraViteConfig( } }); + log.debug('crawl svelte packages result', depsConfig); + // optimize deps extraViteConfig.optimizeDeps = buildOptimizeDepsForSvelte(config); if (options.prebundleSvelteLibraries) { From 036b8de4f4ad17cc7090b5b81a267fc895615746 Mon Sep 17 00:00:00 2001 From: bluwy Date: Tue, 1 Nov 2022 15:06:44 +0800 Subject: [PATCH 04/14] chore: upgrade vitefu --- packages/vite-plugin-svelte/package.json | 2 +- pnpm-lock.yaml | 13 ++++--------- 2 files changed, 5 insertions(+), 10 deletions(-) diff --git a/packages/vite-plugin-svelte/package.json b/packages/vite-plugin-svelte/package.json index eeca66bc1..e9ea1293e 100644 --- a/packages/vite-plugin-svelte/package.json +++ b/packages/vite-plugin-svelte/package.json @@ -51,7 +51,7 @@ "kleur": "^4.1.5", "magic-string": "^0.26.7", "svelte-hmr": "^0.15.0", - "vitefu": "^0.1.0" + "vitefu": "^0.1.1" }, "peerDependencies": { "diff-match-patch": "^1.0.5", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 5c4ac52c6..34cf58004 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -473,14 +473,14 @@ importers: svelte-hmr: ^0.15.0 tsup: ^6.3.0 vite: ^3.2.0 - vitefu: ^0.1.0 + vitefu: ^0.1.1 dependencies: debug: 4.3.4 deepmerge: 4.2.2 kleur: 4.1.5 magic-string: 0.26.7 svelte-hmr: 0.15.0_svelte@3.52.0 - vitefu: 0.1.0_vite@3.2.0 + vitefu: 0.1.1_vite@3.2.0 devDependencies: '@types/debug': 4.1.7 '@types/diff-match-patch': 1.0.32 @@ -3150,10 +3150,6 @@ packages: resolve-from: 4.0.0 dev: true - /import-meta-resolve/2.1.0: - resolution: {integrity: sha512-yG9pxkWJVTy4cmRsNWE3ztFdtFuYIV8G4N+cbCkO8b+qngkLyIUhxQFuZ0qJm67+0nUOxjMPT7nfksPKza1v2g==} - dev: false - /imurmurhash/0.1.4: resolution: {integrity: sha512-JmXMZ6wuvDmLiHEml9ykzqO6lwFbof0GG4IkcGaENdCRDDmMVnny7s5HsIgHCbaq0w2MyPhDqkhTUgS2LU2PHA==} engines: {node: '>=0.8.19'} @@ -5671,15 +5667,14 @@ packages: fsevents: 2.3.2 dev: true - /vitefu/0.1.0_vite@3.2.0: - resolution: {integrity: sha512-5MQSHP9yr0HIve8q4XNb7QXfO1P4tzZDZP99qH0FM5ClcwYddeGXRDQ4TQYRUeXLjZ+vLecirHtGNpwFFUF7sw==} + /vitefu/0.1.1_vite@3.2.0: + resolution: {integrity: sha512-HClD14fjMJ+NQgXBqT3dC3RdO/+Chayil+cCPYZKY3kT+KcJomKzrdgzfCHJkIL2L0OAY+VPvrSW615iPtc7ag==} peerDependencies: vite: ^3.0.0 || ^3.2.0 peerDependenciesMeta: vite: optional: true dependencies: - import-meta-resolve: 2.1.0 vite: 3.2.0 dev: false From ccd49d3a76e0a1b39454e5810d9a5a46333a93c1 Mon Sep 17 00:00:00 2001 From: bluwy Date: Thu, 10 Nov 2022 16:02:42 +0800 Subject: [PATCH 05/14] chore: upgrade vitefu and refactor code --- packages/vite-plugin-svelte/package.json | 2 +- .../vite-plugin-svelte/src/utils/options.ts | 50 ++++++++++--------- pnpm-lock.yaml | 8 +-- 3 files changed, 31 insertions(+), 29 deletions(-) diff --git a/packages/vite-plugin-svelte/package.json b/packages/vite-plugin-svelte/package.json index e9ea1293e..b62c20222 100644 --- a/packages/vite-plugin-svelte/package.json +++ b/packages/vite-plugin-svelte/package.json @@ -51,7 +51,7 @@ "kleur": "^4.1.5", "magic-string": "^0.26.7", "svelte-hmr": "^0.15.0", - "vitefu": "^0.1.1" + "vitefu": "^0.2.0" }, "peerDependencies": { "diff-match-patch": "^1.0.5", diff --git a/packages/vite-plugin-svelte/src/utils/options.ts b/packages/vite-plugin-svelte/src/utils/options.ts index ad8a8f058..10cf07b7d 100644 --- a/packages/vite-plugin-svelte/src/utils/options.ts +++ b/packages/vite-plugin-svelte/src/utils/options.ts @@ -311,7 +311,7 @@ export async function buildExtraViteConfig( options: PreResolvedOptions, config: UserConfig ): Promise> { - const extraViteConfig: Partial = { + let extraViteConfig: Partial = { resolve: { mainFields: [...SVELTE_RESOLVE_MAIN_FIELDS], dedupe: [...SVELTE_IMPORTS, ...SVELTE_HMR_IMPORTS] @@ -345,8 +345,33 @@ export async function buildExtraViteConfig( log.debug('crawl svelte packages result', depsConfig); + if (options.prebundleSvelteLibraries) { + depsConfig.optimizeDeps = { include: [], exclude: [] }; + } else if (options.disableDependencyReinclusion === true) { + depsConfig.optimizeDeps.include = depsConfig.optimizeDeps.include.filter( + (dep) => !dep.includes('>') + ); + } else if (Array.isArray(options.disableDependencyReinclusion)) { + const disabledDeps = options.disableDependencyReinclusion; + const isDisabled = (dep: string) => { + // `crawlFrameworkPkgs` always return `{dep} > {something}` format for deep includes + return disabledDeps.some((disabledDep) => dep.includes(`${disabledDep} >`)); + }; + depsConfig.optimizeDeps.include = depsConfig.optimizeDeps.include.filter( + (dep) => !isDisabled(dep) + ); + } + + log.debug('processed crawl svelte packages result', depsConfig); + // optimize deps extraViteConfig.optimizeDeps = buildOptimizeDepsForSvelte(config); + // ssr config + extraViteConfig.ssr = buildSSROptionsForSvelte(config); + // merge crawl result + extraViteConfig = deepmerge(extraViteConfig, depsConfig); + + // handle prebundling for svelte files if (options.prebundleSvelteLibraries) { extraViteConfig.optimizeDeps = { ...extraViteConfig.optimizeDeps, @@ -360,31 +385,8 @@ export async function buildExtraViteConfig( plugins: [{ name: facadeEsbuildSveltePluginName, setup: () => {} }] } }; - } else { - if (options.disableDependencyReinclusion !== true) { - const disabledReinclusions = options.disableDependencyReinclusion || []; - if (disabledReinclusions.length > 0) { - log.debug(`not reincluding transitive dependencies of`, disabledReinclusions); - } - const transitiveDepsToInclude = depsConfig.optimizeDeps.include.filter((dep) => - disabledReinclusions.every((disabled) => !dep.includes(disabled)) - ); - log.debug( - `reincluding transitive dependencies of excluded svelte dependencies`, - transitiveDepsToInclude - ); - depsConfig.optimizeDeps.include?.push(...transitiveDepsToInclude); - } - extraViteConfig.optimizeDeps.include?.push(...depsConfig.optimizeDeps.include); - extraViteConfig.optimizeDeps.exclude?.push(...depsConfig.optimizeDeps.exclude); } - // ssr config - extraViteConfig.ssr = buildSSROptionsForSvelte(config); - // @ts-expect-error `noExternal` is 100% an array - extraViteConfig.ssr?.noExternal?.push(...depsConfig.ssr.noExternal); - extraViteConfig.ssr?.external?.push(...depsConfig.ssr.external); - // enable hmrPartialAccept if not explicitly disabled if ( (options.hot == null || diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 34cf58004..21e4fc35a 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -473,14 +473,14 @@ importers: svelte-hmr: ^0.15.0 tsup: ^6.3.0 vite: ^3.2.0 - vitefu: ^0.1.1 + vitefu: ^0.2.0 dependencies: debug: 4.3.4 deepmerge: 4.2.2 kleur: 4.1.5 magic-string: 0.26.7 svelte-hmr: 0.15.0_svelte@3.52.0 - vitefu: 0.1.1_vite@3.2.0 + vitefu: 0.2.0_vite@3.2.0 devDependencies: '@types/debug': 4.1.7 '@types/diff-match-patch': 1.0.32 @@ -5667,8 +5667,8 @@ packages: fsevents: 2.3.2 dev: true - /vitefu/0.1.1_vite@3.2.0: - resolution: {integrity: sha512-HClD14fjMJ+NQgXBqT3dC3RdO/+Chayil+cCPYZKY3kT+KcJomKzrdgzfCHJkIL2L0OAY+VPvrSW615iPtc7ag==} + /vitefu/0.2.0_vite@3.2.0: + resolution: {integrity: sha512-58946QxFCr0OnNbF73JPA3nyzfI65G82bWwKV8zxAcQfTeAyGU99ejSFIG7RBUDBUr1RonXI/VEMzIrNl/euXA==} peerDependencies: vite: ^3.0.0 || ^3.2.0 peerDependenciesMeta: From a796df6611dcaa8dec263485d601fb482f821f0f Mon Sep 17 00:00:00 2001 From: bluwy Date: Thu, 10 Nov 2022 16:56:07 +0800 Subject: [PATCH 06/14] fix: safer reinclusion filter --- packages/vite-plugin-svelte/src/utils/options.ts | 12 +++++------- 1 file changed, 5 insertions(+), 7 deletions(-) diff --git a/packages/vite-plugin-svelte/src/utils/options.ts b/packages/vite-plugin-svelte/src/utils/options.ts index 10cf07b7d..cc6f4af4b 100644 --- a/packages/vite-plugin-svelte/src/utils/options.ts +++ b/packages/vite-plugin-svelte/src/utils/options.ts @@ -20,7 +20,7 @@ import type { // eslint-disable-next-line node/no-missing-import } from 'svelte/types/compiler/preprocess'; -import path from 'path'; +import path, { join } from 'path'; import { esbuildSveltePlugin, facadeEsbuildSveltePluginName } from './esbuild'; import { addExtraPreprocessors } from './preprocess'; import deepmerge from 'deepmerge'; @@ -352,13 +352,11 @@ export async function buildExtraViteConfig( (dep) => !dep.includes('>') ); } else if (Array.isArray(options.disableDependencyReinclusion)) { - const disabledDeps = options.disableDependencyReinclusion; - const isDisabled = (dep: string) => { - // `crawlFrameworkPkgs` always return `{dep} > {something}` format for deep includes - return disabledDeps.some((disabledDep) => dep.includes(`${disabledDep} >`)); - }; + const disabledDepsRegex = new RegExp( + options.disableDependencyReinclusion.map((dep) => `(?:>|^)\\s*${dep}\\s*>`).join('|') + ); depsConfig.optimizeDeps.include = depsConfig.optimizeDeps.include.filter( - (dep) => !isDisabled(dep) + (dep) => !disabledDepsRegex.test(dep) ); } From 3fe704ae1c39a8020e28c3abf1c79e2980d4ce12 Mon Sep 17 00:00:00 2001 From: bluwy Date: Thu, 10 Nov 2022 17:05:18 +0800 Subject: [PATCH 07/14] fix: remove unused import --- packages/vite-plugin-svelte/src/utils/options.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/vite-plugin-svelte/src/utils/options.ts b/packages/vite-plugin-svelte/src/utils/options.ts index cc6f4af4b..7db259338 100644 --- a/packages/vite-plugin-svelte/src/utils/options.ts +++ b/packages/vite-plugin-svelte/src/utils/options.ts @@ -20,7 +20,7 @@ import type { // eslint-disable-next-line node/no-missing-import } from 'svelte/types/compiler/preprocess'; -import path, { join } from 'path'; +import path from 'path'; import { esbuildSveltePlugin, facadeEsbuildSveltePluginName } from './esbuild'; import { addExtraPreprocessors } from './preprocess'; import deepmerge from 'deepmerge'; From 2d2b9518e4f82730929fa2ac87884d8dbf374ba4 Mon Sep 17 00:00:00 2001 From: bluwy Date: Thu, 10 Nov 2022 23:25:11 +0800 Subject: [PATCH 08/14] chore: remove regex --- packages/vite-plugin-svelte/src/utils/options.ts | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/packages/vite-plugin-svelte/src/utils/options.ts b/packages/vite-plugin-svelte/src/utils/options.ts index 7db259338..bdcce582a 100644 --- a/packages/vite-plugin-svelte/src/utils/options.ts +++ b/packages/vite-plugin-svelte/src/utils/options.ts @@ -352,12 +352,12 @@ export async function buildExtraViteConfig( (dep) => !dep.includes('>') ); } else if (Array.isArray(options.disableDependencyReinclusion)) { - const disabledDepsRegex = new RegExp( - options.disableDependencyReinclusion.map((dep) => `(?:>|^)\\s*${dep}\\s*>`).join('|') - ); - depsConfig.optimizeDeps.include = depsConfig.optimizeDeps.include.filter( - (dep) => !disabledDepsRegex.test(dep) - ); + const disabledDeps = options.disableDependencyReinclusion; + depsConfig.optimizeDeps.include = depsConfig.optimizeDeps.include.filter((dep) => { + if (!dep.includes('>')) return true; + const trimDep = dep.replace(/\s+/g, ''); + return disabledDeps.some((disabled) => trimDep.includes(`${disabled}>`)); + }); } log.debug('processed crawl svelte packages result', depsConfig); From f5bb42a12b08dc2db5e2f657ded9926b3567d281 Mon Sep 17 00:00:00 2001 From: bluwy Date: Thu, 10 Nov 2022 23:59:12 +0800 Subject: [PATCH 09/14] fix: respect v-p-s added vite config --- .../vite-plugin-svelte/src/utils/options.ts | 132 +++++++++++------- 1 file changed, 78 insertions(+), 54 deletions(-) diff --git a/packages/vite-plugin-svelte/src/utils/options.ts b/packages/vite-plugin-svelte/src/utils/options.ts index bdcce582a..435d70b19 100644 --- a/packages/vite-plugin-svelte/src/utils/options.ts +++ b/packages/vite-plugin-svelte/src/utils/options.ts @@ -24,8 +24,14 @@ import path from 'path'; import { esbuildSveltePlugin, facadeEsbuildSveltePluginName } from './esbuild'; import { addExtraPreprocessors } from './preprocess'; import deepmerge from 'deepmerge'; -// eslint-disable-next-line node/no-missing-import -import { crawlFrameworkPkgs } from 'vitefu'; +import { + crawlFrameworkPkgs, + isDepExcluded, + isDepExternaled, + isDepIncluded, + isDepNoExternaled + // eslint-disable-next-line node/no-missing-import +} from 'vitefu'; import { isCommonDepWithoutSvelteField } from './dependencies'; const allowedPluginOptions = new Set([ @@ -311,7 +317,7 @@ export async function buildExtraViteConfig( options: PreResolvedOptions, config: UserConfig ): Promise> { - let extraViteConfig: Partial = { + const extraViteConfig: Partial = { resolve: { mainFields: [...SVELTE_RESOLVE_MAIN_FIELDS], dedupe: [...SVELTE_IMPORTS, ...SVELTE_HMR_IMPORTS] @@ -322,6 +328,67 @@ export async function buildExtraViteConfig( // knownJsSrcExtensions: options.extensions }; + const optimizeDepsConfig = buildOptimizeDepsForSvelte(config); + const ssrConfig = buildSSROptionsForSvelte(config); + const crawlConfig = await getCrawlPkgsConfig(options, config); + + extraViteConfig.optimizeDeps = { + include: [ + ...optimizeDepsConfig.include, + ...crawlConfig.optimizeDeps.include.filter( + (dep) => !isDepExcluded(dep, optimizeDepsConfig.include) + ) + ], + exclude: [ + ...optimizeDepsConfig.exclude, + ...crawlConfig.optimizeDeps.exclude.filter( + (dep) => !isDepIncluded(dep, optimizeDepsConfig.exclude) + ) + ] + }; + + extraViteConfig.ssr = { + noExternal: [ + ...ssrConfig.noExternal, + ...crawlConfig.ssr.noExternal.filter((dep) => !isDepExternaled(dep, ssrConfig.external)) + ], + external: [ + ...ssrConfig.external, + ...crawlConfig.ssr.external.filter((dep) => !isDepNoExternaled(dep, ssrConfig.noExternal)) + ] + }; + + // handle prebundling for svelte files + if (options.prebundleSvelteLibraries) { + extraViteConfig.optimizeDeps = { + ...extraViteConfig.optimizeDeps, + // Experimental Vite API to allow these extensions to be scanned and prebundled + // @ts-ignore + extensions: options.extensions ?? ['.svelte'], + // Add esbuild plugin to prebundle Svelte files. + // Currently a placeholder as more information is needed after Vite config is resolved, + // the real Svelte plugin is added in `patchResolvedViteConfig()` + esbuildOptions: { + plugins: [{ name: facadeEsbuildSveltePluginName, setup: () => {} }] + } + }; + } + + // enable hmrPartialAccept if not explicitly disabled + if ( + (options.hot == null || + options.hot === true || + (options.hot && options.hot.partialAccept !== false)) && // deviate from svelte-hmr, default to true + config.experimental?.hmrPartialAccept !== false + ) { + log.debug('enabling "experimental.hmrPartialAccept" in vite config'); + extraViteConfig.experimental = { hmrPartialAccept: true }; + } + + return extraViteConfig; +} + +async function getCrawlPkgsConfig(options: PreResolvedOptions, config: UserConfig) { // extra handling for svelte dependencies in the project const depsConfig = await crawlFrameworkPkgs({ root: options.root, @@ -362,77 +429,34 @@ export async function buildExtraViteConfig( log.debug('processed crawl svelte packages result', depsConfig); - // optimize deps - extraViteConfig.optimizeDeps = buildOptimizeDepsForSvelte(config); - // ssr config - extraViteConfig.ssr = buildSSROptionsForSvelte(config); - // merge crawl result - extraViteConfig = deepmerge(extraViteConfig, depsConfig); - - // handle prebundling for svelte files - if (options.prebundleSvelteLibraries) { - extraViteConfig.optimizeDeps = { - ...extraViteConfig.optimizeDeps, - // Experimental Vite API to allow these extensions to be scanned and prebundled - // @ts-ignore - extensions: options.extensions ?? ['.svelte'], - // Add esbuild plugin to prebundle Svelte files. - // Currently a placeholder as more information is needed after Vite config is resolved, - // the real Svelte plugin is added in `patchResolvedViteConfig()` - esbuildOptions: { - plugins: [{ name: facadeEsbuildSveltePluginName, setup: () => {} }] - } - }; - } - - // enable hmrPartialAccept if not explicitly disabled - if ( - (options.hot == null || - options.hot === true || - (options.hot && options.hot.partialAccept !== false)) && // deviate from svelte-hmr, default to true - config.experimental?.hmrPartialAccept !== false - ) { - log.debug('enabling "experimental.hmrPartialAccept" in vite config'); - extraViteConfig.experimental = { hmrPartialAccept: true }; - } - - return extraViteConfig; + return depsConfig; } -function buildOptimizeDepsForSvelte(config: UserConfig): DepOptimizationOptions { +function buildOptimizeDepsForSvelte(config: UserConfig) { // include svelte imports for optimization unless explicitly excluded const include: string[] = []; const exclude: string[] = ['svelte-hmr']; - const isIncluded = (dep: string) => - include.includes(dep) || config.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 - config.optimizeDeps?.exclude?.some((id: string) => dep === id || id.startsWith(`${dep}/`)) - ); - }; - if (!isExcluded('svelte')) { + if (!isDepExcluded('svelte', config.optimizeDeps?.exclude ?? [])) { 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))); + include.push(...svelteImportsToInclude); } else { log.debug('"svelte" is excluded in optimizeDeps.exclude, skipped adding it to include.'); } return { include, exclude }; } -function buildSSROptionsForSvelte(config: UserConfig): any { +function buildSSROptionsForSvelte(config: UserConfig) { const noExternal: (string | RegExp)[] = []; + const external: string[] = []; // add svelte to ssr.noExternal unless it is present in ssr.external // so we can resolve it with svelte/ssr - if (!config.ssr?.external?.includes('svelte')) { + if (!isDepExternaled('svelte', config.ssr?.external ?? [])) { noExternal.push('svelte', /^svelte\//); } - return { noExternal, external: [] }; + return { noExternal, external }; } export function patchResolvedViteConfig(viteConfig: ResolvedConfig, options: ResolvedOptions) { From 35646f27af56a64f251f2a1ea312a6fbcc3ea622 Mon Sep 17 00:00:00 2001 From: bluwy Date: Fri, 11 Nov 2022 00:07:40 +0800 Subject: [PATCH 10/14] fix: lint --- packages/vite-plugin-svelte/src/utils/options.ts | 9 +-------- 1 file changed, 1 insertion(+), 8 deletions(-) diff --git a/packages/vite-plugin-svelte/src/utils/options.ts b/packages/vite-plugin-svelte/src/utils/options.ts index 435d70b19..e88a1092e 100644 --- a/packages/vite-plugin-svelte/src/utils/options.ts +++ b/packages/vite-plugin-svelte/src/utils/options.ts @@ -1,12 +1,5 @@ /* eslint-disable no-unused-vars */ -import { - ConfigEnv, - DepOptimizationOptions, - ResolvedConfig, - UserConfig, - ViteDevServer, - normalizePath -} from 'vite'; +import { ConfigEnv, ResolvedConfig, 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'; From 5e28badbc1a68fe518c7e337a38e488dcb24b06d Mon Sep 17 00:00:00 2001 From: bluwy Date: Fri, 11 Nov 2022 00:10:30 +0800 Subject: [PATCH 11/14] fix: typo --- packages/vite-plugin-svelte/src/utils/options.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/vite-plugin-svelte/src/utils/options.ts b/packages/vite-plugin-svelte/src/utils/options.ts index e88a1092e..10472c50c 100644 --- a/packages/vite-plugin-svelte/src/utils/options.ts +++ b/packages/vite-plugin-svelte/src/utils/options.ts @@ -329,13 +329,13 @@ export async function buildExtraViteConfig( include: [ ...optimizeDepsConfig.include, ...crawlConfig.optimizeDeps.include.filter( - (dep) => !isDepExcluded(dep, optimizeDepsConfig.include) + (dep) => !isDepExcluded(dep, optimizeDepsConfig.exclude) ) ], exclude: [ ...optimizeDepsConfig.exclude, ...crawlConfig.optimizeDeps.exclude.filter( - (dep) => !isDepIncluded(dep, optimizeDepsConfig.exclude) + (dep) => !isDepIncluded(dep, optimizeDepsConfig.include) ) ] }; From 174e1dfadff9eaddd358eb23c6d91b07414ceb43 Mon Sep 17 00:00:00 2001 From: dominikg Date: Thu, 10 Nov 2022 21:40:26 +0100 Subject: [PATCH 12/14] test: add tests for prebundleSvelteLibraries --- .../package-json-svelte-field.spec.ts | 21 +--- .../__tests__/prebundle-svelte-deps.spec.ts | 46 ++++++++ .../prebundle-svelte-deps/index.html | 13 +++ .../prebundle-svelte-deps/package.json | 24 ++++ .../prebundle-svelte-deps/src/App.svelte | 22 ++++ .../prebundle-svelte-deps/src/main.js | 7 ++ .../prebundle-svelte-deps/src/vite-env.d.ts | 2 + .../prebundle-svelte-deps/svelte.config.js | 7 ++ .../prebundle-svelte-deps/vite.config.js | 22 ++++ packages/e2e-tests/testUtils.ts | 17 +++ pnpm-lock.yaml | 109 +++++++++++++++++- 11 files changed, 266 insertions(+), 24 deletions(-) create mode 100644 packages/e2e-tests/prebundle-svelte-deps/__tests__/prebundle-svelte-deps.spec.ts create mode 100644 packages/e2e-tests/prebundle-svelte-deps/index.html create mode 100644 packages/e2e-tests/prebundle-svelte-deps/package.json create mode 100644 packages/e2e-tests/prebundle-svelte-deps/src/App.svelte create mode 100644 packages/e2e-tests/prebundle-svelte-deps/src/main.js create mode 100644 packages/e2e-tests/prebundle-svelte-deps/src/vite-env.d.ts create mode 100644 packages/e2e-tests/prebundle-svelte-deps/svelte.config.js create mode 100644 packages/e2e-tests/prebundle-svelte-deps/vite.config.js diff --git a/packages/e2e-tests/package-json-svelte-field/__tests__/package-json-svelte-field.spec.ts b/packages/e2e-tests/package-json-svelte-field/__tests__/package-json-svelte-field.spec.ts index f82f7350d..04563ab6a 100644 --- a/packages/e2e-tests/package-json-svelte-field/__tests__/package-json-svelte-field.spec.ts +++ b/packages/e2e-tests/package-json-svelte-field/__tests__/package-json-svelte-field.spec.ts @@ -1,6 +1,4 @@ -import fs from 'fs'; -import path from 'path'; -import { getText, isBuild } from '~utils'; +import { getText, isBuild, readVitePrebundleMetadata } from '~utils'; test('should render component imported via svelte field in package.json', async () => { expect(await getText('#test-id')).toBe('svelte field works'); @@ -18,20 +16,3 @@ if (!isBuild) { ); }); } - -function readVitePrebundleMetadata() { - const metadataPaths = [ - '../node_modules/.vite/_metadata.json', - '../node_modules/.vite/deps/_metadata.json' // vite 2.9 - ]; - for (const metadataPath of metadataPaths) { - try { - const vitePrebundleMetadata = path.resolve(__dirname, metadataPath); - const metadataFile = fs.readFileSync(vitePrebundleMetadata, 'utf8'); - return metadataFile; - } catch { - // ignore - } - } - throw new Error('Unable to find vite prebundle metadata'); -} diff --git a/packages/e2e-tests/prebundle-svelte-deps/__tests__/prebundle-svelte-deps.spec.ts b/packages/e2e-tests/prebundle-svelte-deps/__tests__/prebundle-svelte-deps.spec.ts new file mode 100644 index 000000000..1f16d26cf --- /dev/null +++ b/packages/e2e-tests/prebundle-svelte-deps/__tests__/prebundle-svelte-deps.spec.ts @@ -0,0 +1,46 @@ +import { browserLogs, getText, isBuild, readVitePrebundleMetadata } from '~utils'; + +test('should not have failed requests', async () => { + browserLogs.forEach((msg) => { + expect(msg).not.toMatch('404'); + }); +}); + +test('should render Hybrid import', async () => { + expect(await getText('#hybrid .label')).toBe('dependency-import'); +}); + +test('should render Simple import', async () => { + expect(await getText('#hybrid .label')).toBe('dependency-import'); +}); + +test('should render Nested import', async () => { + expect(await getText('#nested #message')).toBe('nested'); + expect(await getText('#nested #cjs-and-esm')).toBe('esm'); +}); + +test('should render api-only import', async () => { + expect(await getText('#api-only')).toBe('api loaded: true'); +}); + +if (!isBuild) { + test('should optimize svelte dependencies and their cjs subdependencies', () => { + const metadataFile = readVitePrebundleMetadata(); + const metadata = JSON.parse(metadataFile); + const optimizedPaths = Object.keys(metadata.optimized); + expect(optimizedPaths).toContain('e2e-test-dep-svelte-simple'); + expect(optimizedPaths).toContain('e2e-test-dep-svelte-hybrid'); + expect(optimizedPaths).toContain('e2e-test-dep-svelte-api-only'); + expect(optimizedPaths).toContain('e2e-test-dep-svelte-hybrid > e2e-test-dep-cjs-only'); + expect(optimizedPaths).toContain( + 'e2e-test-dep-svelte-nested > e2e-test-dep-svelte-simple > e2e-test-dep-cjs-only' + ); + }); + + test('should not optimize excluded svelte dependencies', () => { + const metadataFile = readVitePrebundleMetadata(); + const metadata = JSON.parse(metadataFile); + const optimizedPaths = Object.keys(metadata.optimized); + expect(optimizedPaths).not.toContain('e2e-test-dep-svelte-nested'); + }); +} diff --git a/packages/e2e-tests/prebundle-svelte-deps/index.html b/packages/e2e-tests/prebundle-svelte-deps/index.html new file mode 100644 index 000000000..52b82bfa5 --- /dev/null +++ b/packages/e2e-tests/prebundle-svelte-deps/index.html @@ -0,0 +1,13 @@ + + + + + + + Vite + Svelte + + +
+ + + diff --git a/packages/e2e-tests/prebundle-svelte-deps/package.json b/packages/e2e-tests/prebundle-svelte-deps/package.json new file mode 100644 index 000000000..d8989df3c --- /dev/null +++ b/packages/e2e-tests/prebundle-svelte-deps/package.json @@ -0,0 +1,24 @@ +{ + "name": "e2e-tests-prebundle-svelte-deps", + "private": true, + "version": "0.0.0", + "type": "module", + "scripts": { + "dev": "vite", + "build": "vite build", + "preview": "vite preview" + }, + "dependencies": { + "e2e-test-dep-svelte-api-only": "file:../_test_dependencies/svelte-api-only", + "e2e-test-dep-svelte-hybrid": "file:../_test_dependencies/svelte-hybrid", + "e2e-test-dep-svelte-nested": "file:../_test_dependencies/svelte-nested", + "e2e-test-dep-svelte-simple": "file:../_test_dependencies/svelte-simple" + }, + "devDependencies": { + "@sveltejs/vite-plugin-svelte": "workspace:*", + "sass": "^1.56.0", + "svelte": "^3.52.0", + "svelte-preprocess": "^4.10.7", + "vite": "^3.2.3" + } +} diff --git a/packages/e2e-tests/prebundle-svelte-deps/src/App.svelte b/packages/e2e-tests/prebundle-svelte-deps/src/App.svelte new file mode 100644 index 000000000..2967714b6 --- /dev/null +++ b/packages/e2e-tests/prebundle-svelte-deps/src/App.svelte @@ -0,0 +1,22 @@ + + +
+
+ +
+
+ +
+
+ +
+
api loaded: {apiOnlyLoaded}
+
diff --git a/packages/e2e-tests/prebundle-svelte-deps/src/main.js b/packages/e2e-tests/prebundle-svelte-deps/src/main.js new file mode 100644 index 000000000..2c27a2579 --- /dev/null +++ b/packages/e2e-tests/prebundle-svelte-deps/src/main.js @@ -0,0 +1,7 @@ +import App from './App.svelte'; + +const app = new App({ + target: document.body +}); + +export default app; diff --git a/packages/e2e-tests/prebundle-svelte-deps/src/vite-env.d.ts b/packages/e2e-tests/prebundle-svelte-deps/src/vite-env.d.ts new file mode 100644 index 000000000..4078e7476 --- /dev/null +++ b/packages/e2e-tests/prebundle-svelte-deps/src/vite-env.d.ts @@ -0,0 +1,2 @@ +/// +/// diff --git a/packages/e2e-tests/prebundle-svelte-deps/svelte.config.js b/packages/e2e-tests/prebundle-svelte-deps/svelte.config.js new file mode 100644 index 000000000..34e58b624 --- /dev/null +++ b/packages/e2e-tests/prebundle-svelte-deps/svelte.config.js @@ -0,0 +1,7 @@ +import preprocess from 'svelte-preprocess'; +export default { + preprocess: [preprocess()], + vitePlugin: { + prebundleSvelteLibraries: true + } +}; diff --git a/packages/e2e-tests/prebundle-svelte-deps/vite.config.js b/packages/e2e-tests/prebundle-svelte-deps/vite.config.js new file mode 100644 index 000000000..ce40ed392 --- /dev/null +++ b/packages/e2e-tests/prebundle-svelte-deps/vite.config.js @@ -0,0 +1,22 @@ +import { defineConfig } from 'vite'; +import { svelte } from '@sveltejs/vite-plugin-svelte'; + +// https://vitejs.dev/config/ +export default defineConfig({ + plugins: [svelte()], + optimizeDeps: { + // TODO this must be excluded because nested has an scss dep that prebundle can't handle! + // figure out how to exclude it automatically or at least tell the user about it in a more friendly way + exclude: ['e2e-test-dep-svelte-nested'], + include: [ + // TODO without this, it fails for module.exports in the browser. + // shouldn't prebundling take care of it? + 'e2e-test-dep-svelte-hybrid > e2e-test-dep-cjs-only' + ] + }, + build: { + // make build faster by skipping transforms and minification + target: 'esnext', + minify: false + } +}); diff --git a/packages/e2e-tests/testUtils.ts b/packages/e2e-tests/testUtils.ts index e0aafb4ee..a87cf517c 100644 --- a/packages/e2e-tests/testUtils.ts +++ b/packages/e2e-tests/testUtils.ts @@ -268,3 +268,20 @@ export async function fetchPageText() { throw new Error(`request to ${url} failed with ${res.status} - ${res.statusText}.`); } } + +export function readVitePrebundleMetadata() { + const metadataPaths = [ + 'node_modules/.vite/_metadata.json', + 'node_modules/.vite/deps/_metadata.json' // vite 2.9 + ]; + for (const metadataPath of metadataPaths) { + try { + const vitePrebundleMetadata = path.resolve(testDir, metadataPath); + const metadataFile = fs.readFileSync(vitePrebundleMetadata, 'utf8'); + return metadataFile; + } catch { + // ignore + } + } + throw new Error('Unable to find vite prebundle metadata'); +} diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 3f550ecc9..539d1edd9 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -289,6 +289,29 @@ importers: svelte: 3.52.0 vite: 3.2.3 + packages/e2e-tests/prebundle-svelte-deps: + specifiers: + '@sveltejs/vite-plugin-svelte': workspace:* + e2e-test-dep-svelte-api-only: file:../_test_dependencies/svelte-api-only + e2e-test-dep-svelte-hybrid: file:../_test_dependencies/svelte-hybrid + e2e-test-dep-svelte-nested: file:../_test_dependencies/svelte-nested + e2e-test-dep-svelte-simple: file:../_test_dependencies/svelte-simple + sass: ^1.56.0 + svelte: ^3.52.0 + svelte-preprocess: ^4.10.7 + vite: ^3.2.3 + dependencies: + e2e-test-dep-svelte-api-only: file:packages/e2e-tests/_test_dependencies/svelte-api-only + e2e-test-dep-svelte-hybrid: file:packages/e2e-tests/_test_dependencies/svelte-hybrid + e2e-test-dep-svelte-nested: file:packages/e2e-tests/_test_dependencies/svelte-nested + e2e-test-dep-svelte-simple: file:packages/e2e-tests/_test_dependencies/svelte-simple + devDependencies: + '@sveltejs/vite-plugin-svelte': link:../../vite-plugin-svelte + sass: 1.56.0 + svelte: 3.52.0 + svelte-preprocess: 4.10.7_sass@1.56.0+svelte@3.52.0 + vite: 3.2.3_sass@1.56.0 + packages/e2e-tests/preprocess-with-vite: specifiers: '@sveltejs/vite-plugin-svelte': workspace:* @@ -1855,7 +1878,7 @@ packages: dev: true /concat-map/0.0.1: - resolution: {integrity: sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg==} + resolution: {integrity: sha1-2Klr13/Wjfd5OnMDajug1UBdR3s=} dev: true /console-control-strings/1.1.0: @@ -4585,7 +4608,7 @@ packages: dev: true /sander/0.5.1: - resolution: {integrity: sha1-dB4kXiMfB8r7b98PEzrfohalAq0=} + resolution: {integrity: sha512-3lVqBir7WuKDHGrKRDn/1Ye3kwpXaDOMsiRP1wd6wpZW56gJhsbp5RqQpA6JG/P+pkXizygnr1dKR8vzWaVsfA==} dependencies: es6-promise: 3.3.1 graceful-fs: 4.2.10 @@ -4764,7 +4787,7 @@ packages: dev: true /sorcery/0.10.0: - resolution: {integrity: sha1-iukK19fLBfxZ8asMY3hF1cFaUrc=} + resolution: {integrity: sha512-R5ocFmKZQFfSTstfOtHjJuAwbpGyf9qjQa1egyhvXSbM7emjrtLXtGdZsDJDABC85YBfVvrOiGWKSYXPKdvP1g==} hasBin: true dependencies: buffer-crc32: 0.2.13 @@ -5146,6 +5169,57 @@ packages: typescript: 4.8.4 dev: true + /svelte-preprocess/4.10.7_sass@1.56.0+svelte@3.52.0: + resolution: {integrity: sha512-sNPBnqYD6FnmdBrUmBCaqS00RyCsCpj2BG58A1JBswNF7b0OKviwxqVrOL/CKyJrLSClrSeqQv5BXNg2RUbPOw==} + engines: {node: '>= 9.11.2'} + requiresBuild: true + peerDependencies: + '@babel/core': ^7.10.2 + coffeescript: ^2.5.1 + less: ^3.11.3 || ^4.0.0 + node-sass: '*' + postcss: ^7 || ^8 + postcss-load-config: ^2.1.0 || ^3.0.0 || ^4.0.0 + pug: ^3.0.0 + sass: ^1.26.8 + stylus: ^0.55.0 || ^0.58.0 + sugarss: ^2.0.0 + svelte: ^3.23.0 + typescript: ^3.9.5 || ^4.0.0 + peerDependenciesMeta: + '@babel/core': + optional: true + coffeescript: + optional: true + less: + optional: true + node-sass: + optional: true + postcss: + optional: true + postcss-load-config: + optional: true + pug: + optional: true + sass: + optional: true + stylus: + optional: true + sugarss: + optional: true + typescript: + optional: true + dependencies: + '@types/pug': 2.0.6 + '@types/sass': 1.43.1 + detect-indent: 6.1.0 + magic-string: 0.25.9 + sass: 1.56.0 + sorcery: 0.10.0 + strip-indent: 3.0.0 + svelte: 3.52.0 + dev: true + /svelte-preprocess/4.10.7_svelte@3.52.0: resolution: {integrity: sha512-sNPBnqYD6FnmdBrUmBCaqS00RyCsCpj2BG58A1JBswNF7b0OKviwxqVrOL/CKyJrLSClrSeqQv5BXNg2RUbPOw==} engines: {node: '>= 9.11.2'} @@ -5989,7 +6063,34 @@ packages: version: 1.0.0 dependencies: svelte: 3.52.0 - dev: true + + file:packages/e2e-tests/_test_dependencies/svelte-hybrid: + resolution: {directory: packages/e2e-tests/_test_dependencies/svelte-hybrid, type: directory} + name: e2e-test-dep-svelte-hybrid + version: 1.0.0 + hasBin: true + dependencies: + '@types/node': 18.11.9 + e2e-test-dep-cjs-only: link:packages/e2e-tests/_test_dependencies/cjs-only + dev: false + + file:packages/e2e-tests/_test_dependencies/svelte-nested: + resolution: {directory: packages/e2e-tests/_test_dependencies/svelte-nested, type: directory} + name: e2e-test-dep-svelte-nested + version: 1.0.0 + dependencies: + e2e-test-dep-cjs-and-esm: link:packages/e2e-tests/_test_dependencies/cjs-and-esm + e2e-test-dep-scss-only: link:packages/e2e-tests/_test_dependencies/scss-only + e2e-test-dep-svelte-simple: link:packages/e2e-tests/_test_dependencies/svelte-simple + dev: false + + file:packages/e2e-tests/_test_dependencies/svelte-simple: + resolution: {directory: packages/e2e-tests/_test_dependencies/svelte-simple, type: directory} + name: e2e-test-dep-svelte-simple + version: 1.0.0 + dependencies: + e2e-test-dep-cjs-only: link:packages/e2e-tests/_test_dependencies/cjs-only + dev: false file:packages/e2e-tests/_test_dependencies/vite-plugins: resolution: {directory: packages/e2e-tests/_test_dependencies/vite-plugins, type: directory} From 77389ec576335a96db1ae1d110917b1a1574aa67 Mon Sep 17 00:00:00 2001 From: bluwy Date: Fri, 11 Nov 2022 23:32:02 +0800 Subject: [PATCH 13/14] Revert "test: add tests for prebundleSvelteLibraries" This reverts commit 174e1dfadff9eaddd358eb23c6d91b07414ceb43. --- .../package-json-svelte-field.spec.ts | 21 +++- .../__tests__/prebundle-svelte-deps.spec.ts | 46 -------- .../prebundle-svelte-deps/index.html | 13 --- .../prebundle-svelte-deps/package.json | 24 ---- .../prebundle-svelte-deps/src/App.svelte | 22 ---- .../prebundle-svelte-deps/src/main.js | 7 -- .../prebundle-svelte-deps/src/vite-env.d.ts | 2 - .../prebundle-svelte-deps/svelte.config.js | 7 -- .../prebundle-svelte-deps/vite.config.js | 22 ---- packages/e2e-tests/testUtils.ts | 17 --- pnpm-lock.yaml | 109 +----------------- 11 files changed, 24 insertions(+), 266 deletions(-) delete mode 100644 packages/e2e-tests/prebundle-svelte-deps/__tests__/prebundle-svelte-deps.spec.ts delete mode 100644 packages/e2e-tests/prebundle-svelte-deps/index.html delete mode 100644 packages/e2e-tests/prebundle-svelte-deps/package.json delete mode 100644 packages/e2e-tests/prebundle-svelte-deps/src/App.svelte delete mode 100644 packages/e2e-tests/prebundle-svelte-deps/src/main.js delete mode 100644 packages/e2e-tests/prebundle-svelte-deps/src/vite-env.d.ts delete mode 100644 packages/e2e-tests/prebundle-svelte-deps/svelte.config.js delete mode 100644 packages/e2e-tests/prebundle-svelte-deps/vite.config.js diff --git a/packages/e2e-tests/package-json-svelte-field/__tests__/package-json-svelte-field.spec.ts b/packages/e2e-tests/package-json-svelte-field/__tests__/package-json-svelte-field.spec.ts index 04563ab6a..f82f7350d 100644 --- a/packages/e2e-tests/package-json-svelte-field/__tests__/package-json-svelte-field.spec.ts +++ b/packages/e2e-tests/package-json-svelte-field/__tests__/package-json-svelte-field.spec.ts @@ -1,4 +1,6 @@ -import { getText, isBuild, readVitePrebundleMetadata } from '~utils'; +import fs from 'fs'; +import path from 'path'; +import { getText, isBuild } from '~utils'; test('should render component imported via svelte field in package.json', async () => { expect(await getText('#test-id')).toBe('svelte field works'); @@ -16,3 +18,20 @@ if (!isBuild) { ); }); } + +function readVitePrebundleMetadata() { + const metadataPaths = [ + '../node_modules/.vite/_metadata.json', + '../node_modules/.vite/deps/_metadata.json' // vite 2.9 + ]; + for (const metadataPath of metadataPaths) { + try { + const vitePrebundleMetadata = path.resolve(__dirname, metadataPath); + const metadataFile = fs.readFileSync(vitePrebundleMetadata, 'utf8'); + return metadataFile; + } catch { + // ignore + } + } + throw new Error('Unable to find vite prebundle metadata'); +} diff --git a/packages/e2e-tests/prebundle-svelte-deps/__tests__/prebundle-svelte-deps.spec.ts b/packages/e2e-tests/prebundle-svelte-deps/__tests__/prebundle-svelte-deps.spec.ts deleted file mode 100644 index 1f16d26cf..000000000 --- a/packages/e2e-tests/prebundle-svelte-deps/__tests__/prebundle-svelte-deps.spec.ts +++ /dev/null @@ -1,46 +0,0 @@ -import { browserLogs, getText, isBuild, readVitePrebundleMetadata } from '~utils'; - -test('should not have failed requests', async () => { - browserLogs.forEach((msg) => { - expect(msg).not.toMatch('404'); - }); -}); - -test('should render Hybrid import', async () => { - expect(await getText('#hybrid .label')).toBe('dependency-import'); -}); - -test('should render Simple import', async () => { - expect(await getText('#hybrid .label')).toBe('dependency-import'); -}); - -test('should render Nested import', async () => { - expect(await getText('#nested #message')).toBe('nested'); - expect(await getText('#nested #cjs-and-esm')).toBe('esm'); -}); - -test('should render api-only import', async () => { - expect(await getText('#api-only')).toBe('api loaded: true'); -}); - -if (!isBuild) { - test('should optimize svelte dependencies and their cjs subdependencies', () => { - const metadataFile = readVitePrebundleMetadata(); - const metadata = JSON.parse(metadataFile); - const optimizedPaths = Object.keys(metadata.optimized); - expect(optimizedPaths).toContain('e2e-test-dep-svelte-simple'); - expect(optimizedPaths).toContain('e2e-test-dep-svelte-hybrid'); - expect(optimizedPaths).toContain('e2e-test-dep-svelte-api-only'); - expect(optimizedPaths).toContain('e2e-test-dep-svelte-hybrid > e2e-test-dep-cjs-only'); - expect(optimizedPaths).toContain( - 'e2e-test-dep-svelte-nested > e2e-test-dep-svelte-simple > e2e-test-dep-cjs-only' - ); - }); - - test('should not optimize excluded svelte dependencies', () => { - const metadataFile = readVitePrebundleMetadata(); - const metadata = JSON.parse(metadataFile); - const optimizedPaths = Object.keys(metadata.optimized); - expect(optimizedPaths).not.toContain('e2e-test-dep-svelte-nested'); - }); -} diff --git a/packages/e2e-tests/prebundle-svelte-deps/index.html b/packages/e2e-tests/prebundle-svelte-deps/index.html deleted file mode 100644 index 52b82bfa5..000000000 --- a/packages/e2e-tests/prebundle-svelte-deps/index.html +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - - Vite + Svelte - - -
- - - diff --git a/packages/e2e-tests/prebundle-svelte-deps/package.json b/packages/e2e-tests/prebundle-svelte-deps/package.json deleted file mode 100644 index d8989df3c..000000000 --- a/packages/e2e-tests/prebundle-svelte-deps/package.json +++ /dev/null @@ -1,24 +0,0 @@ -{ - "name": "e2e-tests-prebundle-svelte-deps", - "private": true, - "version": "0.0.0", - "type": "module", - "scripts": { - "dev": "vite", - "build": "vite build", - "preview": "vite preview" - }, - "dependencies": { - "e2e-test-dep-svelte-api-only": "file:../_test_dependencies/svelte-api-only", - "e2e-test-dep-svelte-hybrid": "file:../_test_dependencies/svelte-hybrid", - "e2e-test-dep-svelte-nested": "file:../_test_dependencies/svelte-nested", - "e2e-test-dep-svelte-simple": "file:../_test_dependencies/svelte-simple" - }, - "devDependencies": { - "@sveltejs/vite-plugin-svelte": "workspace:*", - "sass": "^1.56.0", - "svelte": "^3.52.0", - "svelte-preprocess": "^4.10.7", - "vite": "^3.2.3" - } -} diff --git a/packages/e2e-tests/prebundle-svelte-deps/src/App.svelte b/packages/e2e-tests/prebundle-svelte-deps/src/App.svelte deleted file mode 100644 index 2967714b6..000000000 --- a/packages/e2e-tests/prebundle-svelte-deps/src/App.svelte +++ /dev/null @@ -1,22 +0,0 @@ - - -
-
- -
-
- -
-
- -
-
api loaded: {apiOnlyLoaded}
-
diff --git a/packages/e2e-tests/prebundle-svelte-deps/src/main.js b/packages/e2e-tests/prebundle-svelte-deps/src/main.js deleted file mode 100644 index 2c27a2579..000000000 --- a/packages/e2e-tests/prebundle-svelte-deps/src/main.js +++ /dev/null @@ -1,7 +0,0 @@ -import App from './App.svelte'; - -const app = new App({ - target: document.body -}); - -export default app; diff --git a/packages/e2e-tests/prebundle-svelte-deps/src/vite-env.d.ts b/packages/e2e-tests/prebundle-svelte-deps/src/vite-env.d.ts deleted file mode 100644 index 4078e7476..000000000 --- a/packages/e2e-tests/prebundle-svelte-deps/src/vite-env.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -/// -/// diff --git a/packages/e2e-tests/prebundle-svelte-deps/svelte.config.js b/packages/e2e-tests/prebundle-svelte-deps/svelte.config.js deleted file mode 100644 index 34e58b624..000000000 --- a/packages/e2e-tests/prebundle-svelte-deps/svelte.config.js +++ /dev/null @@ -1,7 +0,0 @@ -import preprocess from 'svelte-preprocess'; -export default { - preprocess: [preprocess()], - vitePlugin: { - prebundleSvelteLibraries: true - } -}; diff --git a/packages/e2e-tests/prebundle-svelte-deps/vite.config.js b/packages/e2e-tests/prebundle-svelte-deps/vite.config.js deleted file mode 100644 index ce40ed392..000000000 --- a/packages/e2e-tests/prebundle-svelte-deps/vite.config.js +++ /dev/null @@ -1,22 +0,0 @@ -import { defineConfig } from 'vite'; -import { svelte } from '@sveltejs/vite-plugin-svelte'; - -// https://vitejs.dev/config/ -export default defineConfig({ - plugins: [svelte()], - optimizeDeps: { - // TODO this must be excluded because nested has an scss dep that prebundle can't handle! - // figure out how to exclude it automatically or at least tell the user about it in a more friendly way - exclude: ['e2e-test-dep-svelte-nested'], - include: [ - // TODO without this, it fails for module.exports in the browser. - // shouldn't prebundling take care of it? - 'e2e-test-dep-svelte-hybrid > e2e-test-dep-cjs-only' - ] - }, - build: { - // make build faster by skipping transforms and minification - target: 'esnext', - minify: false - } -}); diff --git a/packages/e2e-tests/testUtils.ts b/packages/e2e-tests/testUtils.ts index a87cf517c..e0aafb4ee 100644 --- a/packages/e2e-tests/testUtils.ts +++ b/packages/e2e-tests/testUtils.ts @@ -268,20 +268,3 @@ export async function fetchPageText() { throw new Error(`request to ${url} failed with ${res.status} - ${res.statusText}.`); } } - -export function readVitePrebundleMetadata() { - const metadataPaths = [ - 'node_modules/.vite/_metadata.json', - 'node_modules/.vite/deps/_metadata.json' // vite 2.9 - ]; - for (const metadataPath of metadataPaths) { - try { - const vitePrebundleMetadata = path.resolve(testDir, metadataPath); - const metadataFile = fs.readFileSync(vitePrebundleMetadata, 'utf8'); - return metadataFile; - } catch { - // ignore - } - } - throw new Error('Unable to find vite prebundle metadata'); -} diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 539d1edd9..3f550ecc9 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -289,29 +289,6 @@ importers: svelte: 3.52.0 vite: 3.2.3 - packages/e2e-tests/prebundle-svelte-deps: - specifiers: - '@sveltejs/vite-plugin-svelte': workspace:* - e2e-test-dep-svelte-api-only: file:../_test_dependencies/svelte-api-only - e2e-test-dep-svelte-hybrid: file:../_test_dependencies/svelte-hybrid - e2e-test-dep-svelte-nested: file:../_test_dependencies/svelte-nested - e2e-test-dep-svelte-simple: file:../_test_dependencies/svelte-simple - sass: ^1.56.0 - svelte: ^3.52.0 - svelte-preprocess: ^4.10.7 - vite: ^3.2.3 - dependencies: - e2e-test-dep-svelte-api-only: file:packages/e2e-tests/_test_dependencies/svelte-api-only - e2e-test-dep-svelte-hybrid: file:packages/e2e-tests/_test_dependencies/svelte-hybrid - e2e-test-dep-svelte-nested: file:packages/e2e-tests/_test_dependencies/svelte-nested - e2e-test-dep-svelte-simple: file:packages/e2e-tests/_test_dependencies/svelte-simple - devDependencies: - '@sveltejs/vite-plugin-svelte': link:../../vite-plugin-svelte - sass: 1.56.0 - svelte: 3.52.0 - svelte-preprocess: 4.10.7_sass@1.56.0+svelte@3.52.0 - vite: 3.2.3_sass@1.56.0 - packages/e2e-tests/preprocess-with-vite: specifiers: '@sveltejs/vite-plugin-svelte': workspace:* @@ -1878,7 +1855,7 @@ packages: dev: true /concat-map/0.0.1: - resolution: {integrity: sha1-2Klr13/Wjfd5OnMDajug1UBdR3s=} + resolution: {integrity: sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg==} dev: true /console-control-strings/1.1.0: @@ -4608,7 +4585,7 @@ packages: dev: true /sander/0.5.1: - resolution: {integrity: sha512-3lVqBir7WuKDHGrKRDn/1Ye3kwpXaDOMsiRP1wd6wpZW56gJhsbp5RqQpA6JG/P+pkXizygnr1dKR8vzWaVsfA==} + resolution: {integrity: sha1-dB4kXiMfB8r7b98PEzrfohalAq0=} dependencies: es6-promise: 3.3.1 graceful-fs: 4.2.10 @@ -4787,7 +4764,7 @@ packages: dev: true /sorcery/0.10.0: - resolution: {integrity: sha512-R5ocFmKZQFfSTstfOtHjJuAwbpGyf9qjQa1egyhvXSbM7emjrtLXtGdZsDJDABC85YBfVvrOiGWKSYXPKdvP1g==} + resolution: {integrity: sha1-iukK19fLBfxZ8asMY3hF1cFaUrc=} hasBin: true dependencies: buffer-crc32: 0.2.13 @@ -5169,57 +5146,6 @@ packages: typescript: 4.8.4 dev: true - /svelte-preprocess/4.10.7_sass@1.56.0+svelte@3.52.0: - resolution: {integrity: sha512-sNPBnqYD6FnmdBrUmBCaqS00RyCsCpj2BG58A1JBswNF7b0OKviwxqVrOL/CKyJrLSClrSeqQv5BXNg2RUbPOw==} - engines: {node: '>= 9.11.2'} - requiresBuild: true - peerDependencies: - '@babel/core': ^7.10.2 - coffeescript: ^2.5.1 - less: ^3.11.3 || ^4.0.0 - node-sass: '*' - postcss: ^7 || ^8 - postcss-load-config: ^2.1.0 || ^3.0.0 || ^4.0.0 - pug: ^3.0.0 - sass: ^1.26.8 - stylus: ^0.55.0 || ^0.58.0 - sugarss: ^2.0.0 - svelte: ^3.23.0 - typescript: ^3.9.5 || ^4.0.0 - peerDependenciesMeta: - '@babel/core': - optional: true - coffeescript: - optional: true - less: - optional: true - node-sass: - optional: true - postcss: - optional: true - postcss-load-config: - optional: true - pug: - optional: true - sass: - optional: true - stylus: - optional: true - sugarss: - optional: true - typescript: - optional: true - dependencies: - '@types/pug': 2.0.6 - '@types/sass': 1.43.1 - detect-indent: 6.1.0 - magic-string: 0.25.9 - sass: 1.56.0 - sorcery: 0.10.0 - strip-indent: 3.0.0 - svelte: 3.52.0 - dev: true - /svelte-preprocess/4.10.7_svelte@3.52.0: resolution: {integrity: sha512-sNPBnqYD6FnmdBrUmBCaqS00RyCsCpj2BG58A1JBswNF7b0OKviwxqVrOL/CKyJrLSClrSeqQv5BXNg2RUbPOw==} engines: {node: '>= 9.11.2'} @@ -6063,34 +5989,7 @@ packages: version: 1.0.0 dependencies: svelte: 3.52.0 - - file:packages/e2e-tests/_test_dependencies/svelte-hybrid: - resolution: {directory: packages/e2e-tests/_test_dependencies/svelte-hybrid, type: directory} - name: e2e-test-dep-svelte-hybrid - version: 1.0.0 - hasBin: true - dependencies: - '@types/node': 18.11.9 - e2e-test-dep-cjs-only: link:packages/e2e-tests/_test_dependencies/cjs-only - dev: false - - file:packages/e2e-tests/_test_dependencies/svelte-nested: - resolution: {directory: packages/e2e-tests/_test_dependencies/svelte-nested, type: directory} - name: e2e-test-dep-svelte-nested - version: 1.0.0 - dependencies: - e2e-test-dep-cjs-and-esm: link:packages/e2e-tests/_test_dependencies/cjs-and-esm - e2e-test-dep-scss-only: link:packages/e2e-tests/_test_dependencies/scss-only - e2e-test-dep-svelte-simple: link:packages/e2e-tests/_test_dependencies/svelte-simple - dev: false - - file:packages/e2e-tests/_test_dependencies/svelte-simple: - resolution: {directory: packages/e2e-tests/_test_dependencies/svelte-simple, type: directory} - name: e2e-test-dep-svelte-simple - version: 1.0.0 - dependencies: - e2e-test-dep-cjs-only: link:packages/e2e-tests/_test_dependencies/cjs-only - dev: false + dev: true file:packages/e2e-tests/_test_dependencies/vite-plugins: resolution: {directory: packages/e2e-tests/_test_dependencies/vite-plugins, type: directory} From d19e05058231dd5f12050123bb3fb3e25f49e1ab Mon Sep 17 00:00:00 2001 From: bluwy Date: Fri, 11 Nov 2022 23:46:02 +0800 Subject: [PATCH 14/14] chore: remove utilities --- packages/vite-plugin-svelte/src/index.ts | 6 ++++-- .../vite-plugin-svelte/src/utils/optimizer.ts | 17 ----------------- 2 files changed, 4 insertions(+), 19 deletions(-) diff --git a/packages/vite-plugin-svelte/src/index.ts b/packages/vite-plugin-svelte/src/index.ts index c8a65bed2..b3f034920 100644 --- a/packages/vite-plugin-svelte/src/index.ts +++ b/packages/vite-plugin-svelte/src/index.ts @@ -1,5 +1,7 @@ import fs from 'fs'; import { HmrContext, ModuleNode, Plugin, ResolvedConfig, UserConfig } from 'vite'; +// eslint-disable-next-line node/no-missing-import +import { isDepExcluded } from 'vitefu'; import { handleHotUpdate } from './handle-hot-update'; import { log, logCompilerWarnings } from './utils/log'; import { CompileData, createCompileSvelte } from './utils/compile'; @@ -19,7 +21,7 @@ import { ensureWatchedFile, setupWatchers } from './utils/watch'; import { resolveViaPackageJsonSvelte } from './utils/resolve'; import { PartialResolvedId } from 'rollup'; import { toRollupError } from './utils/error'; -import { isOptimizeExcluded, saveSvelteMetadata } from './utils/optimizer'; +import { saveSvelteMetadata } from './utils/optimizer'; import { svelteInspector } from './ui/inspector/plugin'; interface PluginAPI { @@ -160,7 +162,7 @@ export function svelte(inlineOptions?: Partial): Plugin[] { options.prebundleSvelteLibraries && viteConfig.optimizeDeps?.disabled !== true && viteConfig.optimizeDeps?.disabled !== (options.isBuild ? 'build' : 'dev') && - !isOptimizeExcluded(importee, viteConfig.optimizeDeps?.exclude); + !isDepExcluded(importee, viteConfig.optimizeDeps?.exclude ?? []); // for prebundled libraries we let vite resolve the prebundling result // for ssr, during scanning and non-prebundled, we do it if (ssr || scan || !isPrebundled) { diff --git a/packages/vite-plugin-svelte/src/utils/optimizer.ts b/packages/vite-plugin-svelte/src/utils/optimizer.ts index 6b1cb2ee7..34e97bcfc 100644 --- a/packages/vite-plugin-svelte/src/utils/optimizer.ts +++ b/packages/vite-plugin-svelte/src/utils/optimizer.ts @@ -43,20 +43,3 @@ function generateSvelteMetadata(options: ResolvedOptions) { } return metadata; } - -// vite optimizeDeps.exclude works for subpackages too -// see https://github.com/vitejs/vite/blob/c87763c1418d1ba876eae13d139eba83ac6f28b2/packages/vite/src/node/optimizer/scan.ts#L293 -export function isOptimizeExcluded(dep: string, exclude?: string[]): boolean { - return !!exclude?.some((e) => dep === e || dep.startsWith(`${e}/`)); -} - -// include can contain `a > b` entries, so we have to test the last segment too -export function isOptimizeIncluded(dep: string, include?: string[]): boolean { - return !!include?.some((e) => { - if (e === dep) { - return true; - } - const lastArrow = e.lastIndexOf('>'); - return lastArrow > -1 && e.slice(lastArrow + 1).trim() === dep; - }); -}