Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: use vitefu to handle svelte libraries #478

Merged
merged 18 commits into from
Nov 11, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/loud-cameras-double.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@sveltejs/vite-plugin-svelte': patch
---

Refactor Svelte libraries config handling
3 changes: 2 additions & 1 deletion packages/vite-plugin-svelte/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,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.2.0"
},
"peerDependencies": {
"diff-match-patch": "^1.0.5",
Expand Down
10 changes: 6 additions & 4 deletions packages/vite-plugin-svelte/src/index.ts
Original file line number Diff line number Diff line change
@@ -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';
Expand All @@ -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 {
Expand Down Expand Up @@ -68,7 +70,7 @@ export function svelte(inlineOptions?: Partial<Options>): 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;
},
Expand Down Expand Up @@ -160,12 +162,12 @@ export function svelte(inlineOptions?: Partial<Options>): 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) {
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}`
Expand Down

This file was deleted.

190 changes: 17 additions & 173 deletions packages/vite-plugin-svelte/src/utils/dependencies.ts
Original file line number Diff line number Diff line change
@@ -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<string, any>;
}

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<DependencyData | undefined> {
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',
Expand Down Expand Up @@ -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(
Expand All @@ -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;
}
17 changes: 0 additions & 17 deletions packages/vite-plugin-svelte/src/utils/optimizer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
});
}
Loading