Skip to content

Commit

Permalink
refactor: debug (#749)
Browse files Browse the repository at this point in the history
* refactor(debug): make it easier to get debug logs without being spammy

* fix: update docs to use correct namespace

* remove very noisy log about css hash
  • Loading branch information
dominikg authored Sep 16, 2023
1 parent 15d9562 commit 7758c8b
Show file tree
Hide file tree
Showing 11 changed files with 65 additions and 29 deletions.
5 changes: 5 additions & 0 deletions .changeset/poor-wasps-worry.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@sveltejs/vite-plugin-svelte': major
---

breaking(debug): remove 'vite:' and add suffixes to debug namespace
2 changes: 1 addition & 1 deletion docs/faq.md
Original file line number Diff line number Diff line change
Expand Up @@ -167,7 +167,7 @@ export default {
There is no golden rule, but you can follow these recommendations:

1. **Never** combine plugins or preprocessors that rewrite imports with prebundling
2. Start with index imports and if your dev-server or build process feels slow, run the process with `DEBUG="vite:vite-plugin-svelte:stats"` to check compile stats to see if switching to deep imports can improve the experience.
2. Start with index imports and if your dev-server or build process feels slow, run the process with `DEBUG="vite-plugin-svelte:stats"` to check compile stats to see if switching to deep imports can improve the experience.
3. Do not mix deep and index imports for the same library, use one style consistently.
4. Use different import styles for different libraries where it helps. E.g. deep imports for the few icons of that one huge icon library, but index import for the component library that is heavily used.

Expand Down
20 changes: 15 additions & 5 deletions packages/vite-plugin-svelte/src/handle-hot-update.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,11 @@ import { toRollupError } from './utils/error.js';
export async function handleHotUpdate(compileSvelte, ctx, svelteRequest, cache, options) {
if (!cache.has(svelteRequest)) {
// file hasn't been requested yet (e.g. async component)
log.debug(`handleHotUpdate called before initial transform for ${svelteRequest.id}`);
log.debug(
`handleHotUpdate called before initial transform for ${svelteRequest.id}`,
undefined,
'hmr'
);
return;
}
const { read, server, modules } = ctx;
Expand All @@ -39,15 +43,15 @@ export async function handleHotUpdate(compileSvelte, ctx, svelteRequest, cache,
if (cssIdx > -1) {
const cssUpdated = cssChanged(cachedCss, compileData.compiled.css);
if (!cssUpdated) {
log.debug(`skipping unchanged css for ${svelteRequest.cssId}`);
log.debug(`skipping unchanged css for ${svelteRequest.cssId}`, undefined, 'hmr');
affectedModules.splice(cssIdx, 1);
}
}
const jsIdx = modules.findIndex((m) => m.id === svelteRequest.id);
if (jsIdx > -1) {
const jsUpdated = jsChanged(cachedJS, compileData.compiled.js, svelteRequest.filename);
if (!jsUpdated) {
log.debug(`skipping unchanged js for ${svelteRequest.id}`);
log.debug(`skipping unchanged js for ${svelteRequest.id}`, undefined, 'hmr');
affectedModules.splice(jsIdx, 1);
// transform won't be called, log warnings here
logCompilerWarnings(svelteRequest, compileData.compiled.warnings, options);
Expand All @@ -57,14 +61,20 @@ export async function handleHotUpdate(compileSvelte, ctx, svelteRequest, cache,
// TODO is this enough? see also: https://github.com/vitejs/vite/issues/2274
const ssrModulesToInvalidate = affectedModules.filter((m) => !!m.ssrTransformResult);
if (ssrModulesToInvalidate.length > 0) {
log.debug(`invalidating modules ${ssrModulesToInvalidate.map((m) => m.id).join(', ')}`);
log.debug(
`invalidating modules ${ssrModulesToInvalidate.map((m) => m.id).join(', ')}`,
undefined,
'hmr'
);
ssrModulesToInvalidate.forEach((moduleNode) => server.moduleGraph.invalidateModule(moduleNode));
}
if (affectedModules.length > 0) {
log.debug(
`handleHotUpdate for ${svelteRequest.id} result: ${affectedModules
.map((m) => m.id)
.join(', ')}`
.join(', ')}`,
undefined,
'hmr'
);
}
return affectedModules;
Expand Down
14 changes: 8 additions & 6 deletions packages/vite-plugin-svelte/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ export function svelte(inlineOptions) {
options = await preResolveOptions(inlineOptions, config, configEnv);
// extra vite config
const extraViteConfig = await buildExtraViteConfig(options, config);
log.debug('additional vite config', extraViteConfig);
log.debug('additional vite config', extraViteConfig, 'config');
return extraViteConfig;
},

Expand All @@ -69,7 +69,7 @@ export function svelte(inlineOptions) {
viteConfig = config;
// TODO deep clone to avoid mutability from outside?
api.options = options;
log.debug('resolved options', options);
log.debug('resolved options', options, 'config');
},

async buildStart() {
Expand Down Expand Up @@ -105,13 +105,12 @@ export function svelte(inlineOptions) {
if (query.svelte && query.type === 'style') {
const css = cache.getCSS(svelteRequest);
if (css) {
log.debug(`load returns css for ${filename}`);
return css;
}
}
// prevent vite asset plugin from loading files as url that should be compiled in transform
if (viteConfig.assetsInclude(filename)) {
log.debug(`load returns raw content for ${filename}`);
log.debug(`load returns raw content for ${filename}`, undefined, 'load');
return fs.readFileSync(filename, 'utf-8');
}
}
Expand All @@ -125,7 +124,11 @@ export function svelte(inlineOptions) {
if (svelteRequest.query.type === 'style' && !svelteRequest.raw) {
// return cssId with root prefix so postcss pipeline of vite finds the directory correctly
// see https://github.com/sveltejs/vite-plugin-svelte/issues/14
log.debug(`resolveId resolved virtual css module ${svelteRequest.cssId}`);
log.debug(
`resolveId resolved virtual css module ${svelteRequest.cssId}`,
undefined,
'resolve'
);
return svelteRequest.cssId;
}
}
Expand Down Expand Up @@ -157,7 +160,6 @@ export function svelte(inlineOptions) {
}
}
}
log.debug(`transform returns compiled js for ${svelteRequest.filename}`);
return {
...compileData.compiled.js,
meta: {
Expand Down
5 changes: 3 additions & 2 deletions packages/vite-plugin-svelte/src/utils/compile.js
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,6 @@ export const _createCompileSvelte = (makeHot) => {

if (options.hot && options.emitCss) {
const hash = `s-${safeBase64Hash(normalizedFilename)}`;
log.debug(`setting cssHash ${hash} for ${normalizedFilename}`);
compileOptions.cssHash = () => hash;
}
if (ssr && compileOptions.enableSourcemap !== false) {
Expand Down Expand Up @@ -107,7 +106,9 @@ export const _createCompileSvelte = (makeHot) => {
});
if (dynamicCompileOptions && log.debug.enabled) {
log.debug(
`dynamic compile options for ${filename}: ${JSON.stringify(dynamicCompileOptions)}`
`dynamic compile options for ${filename}: ${JSON.stringify(dynamicCompileOptions)}`,
undefined,
'compile'
);
}
const finalCompileOptions = dynamicCompileOptions
Expand Down
4 changes: 2 additions & 2 deletions packages/vite-plugin-svelte/src/utils/load-raw.js
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ export async function loadRaw(svelteRequest, compileSvelte, options) {
}" combined with direct in ${id}. supported are: ${supportedDirectTypes.join(', ')}`
);
}
log.debug(`load returns direct result for ${id}`);
log.debug(`load returns direct result for ${id}`, undefined, 'load');
let directOutput = result.code;
if (query.sourcemap && result.map?.toUrl) {
const map = `sourceMappingURL=${result.map.toUrl()}`;
Expand All @@ -76,7 +76,7 @@ export async function loadRaw(svelteRequest, compileSvelte, options) {
}
return directOutput;
} else if (query.raw) {
log.debug(`load returns raw result for ${id}`);
log.debug(`load returns raw result for ${id}`, undefined, 'load');
return toRawExports(result);
} else {
throw new Error(`invalid raw mode in ${id}, supported are raw, direct`);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,7 @@ function findConfigToLoad(viteConfig, inlineOptions) {
.map((candidate) => path.resolve(root, candidate))
.filter((file) => fs.existsSync(file));
if (existingKnownConfigFiles.length === 0) {
log.debug(`no svelte config found at ${root}`);
log.debug(`no svelte config found at ${root}`, undefined, 'config');
return;
} else if (existingKnownConfigFiles.length > 1) {
log.warn(
Expand Down
12 changes: 9 additions & 3 deletions packages/vite-plugin-svelte/src/utils/log.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ const prefix = 'vite-plugin-svelte';
/** @type {Record<import('../types/log.d.ts').LogLevel, any>} */
const loggers = {
debug: {
log: debug(`vite:${prefix}`),
log: debug(`${prefix}`),
enabled: false,
isDebug: true
},
Expand Down Expand Up @@ -65,7 +65,13 @@ function _log(logger, message, payload, namespace) {
return;
}
if (logger.isDebug) {
const log = namespace ? logger.log.extend(namespace) : logger.log;
let log = logger.log;
if (namespace) {
if (!isDebugNamespaceEnabled(namespace)) {
return;
}
log = logger.log.extend(namespace);
}
payload !== undefined ? log(message, payload) : log(message);
} else {
logger.log(
Expand Down Expand Up @@ -251,5 +257,5 @@ export function buildExtendedLogMessage(w) {
* @returns {boolean}
*/
export function isDebugNamespaceEnabled(namespace) {
return debug.enabled(`vite:${prefix}:${namespace}`);
return debug.enabled(`${prefix}:${namespace}`);
}
16 changes: 11 additions & 5 deletions packages/vite-plugin-svelte/src/utils/options.js
Original file line number Diff line number Diff line change
Expand Up @@ -429,7 +429,7 @@ export async function buildExtraViteConfig(options, config) {
(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');
log.debug('enabling "experimental.hmrPartialAccept" in vite config', undefined, 'config');
extraViteConfig.experimental = { hmrPartialAccept: true };
}
validateViteConfig(extraViteConfig, config, options);
Expand Down Expand Up @@ -526,7 +526,7 @@ async function buildExtraConfigForDependencies(options, config) {
].join('\n')}\n\nPlease see ${FAQ_LINK_MISSING_EXPORTS_CONDITION} for details.`
);
}
log.debug('extra config for dependencies generated by vitefu', depsConfig);
log.debug('extra config for dependencies generated by vitefu', depsConfig, 'config');

if (options.prebundleSvelteLibraries) {
// prebundling enabled, so we don't need extra dependency excludes
Expand Down Expand Up @@ -560,7 +560,7 @@ async function buildExtraConfigForDependencies(options, config) {
});
}

log.debug('post-processed extra config for dependencies', depsConfig);
log.debug('post-processed extra config for dependencies', depsConfig, 'config');

return depsConfig;
}
Expand All @@ -577,11 +577,17 @@ function buildExtraConfigForSvelte(config) {
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(', ')} `
`adding bare svelte packages to optimizeDeps.include: ${svelteImportsToInclude.join(', ')} `,
undefined,
'config'
);
include.push(...svelteImportsToInclude);
} else {
log.debug('"svelte" is excluded in optimizeDeps.exclude, skipped adding it to include.');
log.debug(
'"svelte" is excluded in optimizeDeps.exclude, skipped adding it to include.',
undefined,
'config'
);
}
/** @type {(string | RegExp)[]} */
const noExternal = [];
Expand Down
8 changes: 6 additions & 2 deletions packages/vite-plugin-svelte/src/utils/preprocess.js
Original file line number Diff line number Diff line change
Expand Up @@ -84,14 +84,18 @@ function buildExtraPreprocessors(options, config) {
log.debug(
`Ignoring svelte preprocessors defined by these vite plugins: ${ignored
.map((p) => p.name)
.join(', ')}`
.join(', ')}`,
undefined,
'preprocess'
);
}
if (included.length > 0) {
log.debug(
`Adding svelte preprocessors defined by these vite plugins: ${included
.map((p) => p.name)
.join(', ')}`
.join(', ')}`,
undefined,
'preprocess'
);
appendPreprocessors.push(...pluginsWithPreprocessors.map((p) => p.api.sveltePreprocess));
}
Expand Down
6 changes: 4 additions & 2 deletions packages/vite-plugin-svelte/src/utils/watch.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,9 @@ export function setupWatchers(options, cache, requestParser) {
dependants.forEach((dependant) => {
if (fs.existsSync(dependant)) {
log.debug(
`emitting virtual change event for "${dependant}" because depdendency "${filename}" changed`
`emitting virtual change event for "${dependant}" because depdendency "${filename}" changed`,
undefined,
'hmr'
);
watcher.emit('change', dependant);
}
Expand All @@ -34,7 +36,7 @@ export function setupWatchers(options, cache, requestParser) {
if (svelteRequest) {
const removedFromCache = cache.remove(svelteRequest);
if (removedFromCache) {
log.debug(`cleared VitePluginSvelteCache for deleted file ${filename}`);
log.debug(`cleared VitePluginSvelteCache for deleted file ${filename}`, undefined, 'hmr');
}
}
};
Expand Down

0 comments on commit 7758c8b

Please sign in to comment.