Skip to content

Commit 673cf61

Browse files
authored
feat: log compiler warnings to console (#45)
* fix: enable logging of compiler warnings * remove todo * refactor: use own logging instead of vites rollup warn handling to avoid context issues in handleHotUpdate and gain more control over output * add changeset * fix build error due to missing export
1 parent 24ae093 commit 673cf61

File tree

7 files changed

+92
-19
lines changed

7 files changed

+92
-19
lines changed

.changeset/selfish-experts-rest.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
'@sveltejs/vite-plugin-svelte': patch
3+
---
4+
5+
enable logging for compiler warnings

.changeset/wise-impalas-glow.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
'@sveltejs/vite-plugin-svelte': minor
3+
---
4+
5+
Feature: log svelte compiler warnings to console. use options.onwarn to customize logging

packages/vite-plugin-svelte/src/handleHotUpdate.ts

Lines changed: 11 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import { ModuleNode, HmrContext } from 'vite';
22
import { Code, CompileData } from './utils/compile';
3-
import { log } from './utils/log';
3+
import { log, logCompilerWarnings } from './utils/log';
44
import { SvelteRequest } from './utils/id';
55
import { VitePluginSvelteCache } from './utils/VitePluginSvelteCache';
66
import { ResolvedOptions } from './utils/options';
@@ -13,7 +13,7 @@ export async function handleHotUpdate(
1313
ctx: HmrContext,
1414
svelteRequest: SvelteRequest,
1515
cache: VitePluginSvelteCache,
16-
options: Partial<ResolvedOptions>
16+
options: ResolvedOptions
1717
): Promise<ModuleNode[] | void> {
1818
const { read, server } = ctx;
1919

@@ -33,16 +33,22 @@ export async function handleHotUpdate(
3333

3434
const cssModule = server.moduleGraph.getModuleById(svelteRequest.cssId);
3535
const mainModule = server.moduleGraph.getModuleById(svelteRequest.id);
36-
if (cssModule && cssChanged(cachedCss, compileData.compiled.css)) {
36+
const cssUpdated = cssModule && cssChanged(cachedCss, compileData.compiled.css);
37+
if (cssUpdated) {
3738
log.debug('handleHotUpdate css changed');
3839
affectedModules.add(cssModule);
3940
}
40-
41-
if (mainModule && jsChanged(cachedJS, compileData.compiled.js, svelteRequest.filename)) {
41+
const jsUpdated = mainModule && jsChanged(cachedJS, compileData.compiled.js, svelteRequest.filename);
42+
if (jsUpdated) {
4243
log.debug('handleHotUpdate js changed');
4344
affectedModules.add(mainModule);
4445
}
4546

47+
if(!jsUpdated) {
48+
// transform won't be called, log warnings here
49+
logCompilerWarnings(compileData.compiled.warnings,options)
50+
}
51+
4652
const result = [...affectedModules].filter(Boolean) as ModuleNode[];
4753
log.debug(`handleHotUpdate result for ${svelteRequest.id}`, result);
4854

packages/vite-plugin-svelte/src/index.ts

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,9 @@
11
import * as path from 'path';
22
import { HmrContext, IndexHtmlTransformContext, ModuleNode, Plugin, UserConfig } from 'vite';
3-
43
// @ts-ignore
54
import * as relative from 'require-relative';
6-
75
import { handleHotUpdate } from './handleHotUpdate';
8-
import { log } from './utils/log';
6+
import { log, logCompilerWarnings } from './utils/log';
97
import { CompileData, createCompileSvelte } from './utils/compile';
108
import { buildIdParser, IdParser, SvelteRequest } from './utils/id';
119
import {
@@ -29,7 +27,8 @@ export {
2927
Arrayable,
3028
MarkupPreprocessor,
3129
ModuleFormat,
32-
Processed
30+
Processed,
31+
Warning
3332
} from './utils/options';
3433

3534
// extend the Vite plugin interface to be able to have `sveltePreprocess` injection
@@ -203,7 +202,7 @@ export default function vitePluginSvelte(inlineOptions?: Partial<Options>): Plug
203202
throw new Error(`failed to transform tagged svelte request for id ${id}`);
204203
}
205204
const compileData = await compileSvelte(svelteRequest, code, options);
206-
205+
logCompilerWarnings(compileData.compiled.warnings, options);
207206
cache.update(compileData);
208207
if (compileData.dependencies?.length && options.server) {
209208
compileData.dependencies.forEach((d) => this.addWatchFile(d));

packages/vite-plugin-svelte/src/utils/compile.ts

Lines changed: 1 addition & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ const _createCompileSvelte = (makeHot: Function) =>
1313
options: Partial<ResolvedOptions>
1414
): Promise<CompileData> {
1515
const { filename, normalizedFilename, cssId, ssr } = svelteRequest;
16-
const { onwarn, emitCss = true } = options;
16+
const { emitCss = true } = options;
1717
const dependencies = [];
1818
const finalCompilerOptions: CompileOptions = {
1919
...options.compilerOptions,
@@ -36,13 +36,6 @@ const _createCompileSvelte = (makeHot: Function) =>
3636

3737
const compiled = compile(preprocessed ? preprocessed.code : code, finalCompilerOptions);
3838

39-
(compiled.warnings || []).forEach((warning) => {
40-
if (!emitCss && warning.code === 'css-unused-selector') return;
41-
// TODO handle warnings
42-
if (onwarn) onwarn(warning /*, this.warn*/);
43-
//else this.warn(warning)
44-
});
45-
4639
if (emitCss && compiled.css.code) {
4740
// TODO properly update sourcemap?
4841
compiled.js.code += `\nimport ${JSON.stringify(cssId)};\n`;

packages/vite-plugin-svelte/src/utils/log.ts

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
/* eslint-disable no-unused-vars */
22
import chalk from 'chalk';
33
import debug from 'debug';
4+
import {ResolvedOptions, Warning} from "./options";
5+
46
const levels: string[] = ['debug', 'info', 'warn', 'error', 'silent'];
57
const prefix = 'vite-plugin-svelte';
68
const loggers: { [key: string]: any } = {
@@ -93,3 +95,44 @@ export const log = {
9395
// TODO still needed?
9496
setViteLogOverwriteProtection
9597
};
98+
99+
100+
export function logCompilerWarnings(
101+
warnings: Warning[],
102+
options: ResolvedOptions
103+
) {
104+
const {emitCss,onwarn, isBuild} = options;
105+
const warn = isBuild ? warnBuild : warnDev;
106+
warnings?.forEach(warning => {
107+
if (!emitCss && warning.code === 'css-unused-selector'){
108+
return;
109+
}
110+
if (onwarn) {
111+
onwarn(warning , warn);
112+
} else {
113+
warn(warning)
114+
}
115+
})
116+
}
117+
118+
function warnDev(w: Warning) {
119+
log.info.enabled && log.info(buildExtendedLogMessage(w))
120+
}
121+
122+
function warnBuild(w: Warning) {
123+
log.warn.enabled && log.warn(buildExtendedLogMessage(w),w.frame)
124+
}
125+
126+
function buildExtendedLogMessage(w: Warning) {
127+
const parts = [];
128+
if(w.filename) {
129+
parts.push(w.filename)
130+
}
131+
if(w.start) {
132+
parts.push(':',w.start.line,':',w.start.column)
133+
}
134+
if(w.message){
135+
parts.push(' ',w.message)
136+
}
137+
return parts.join('');
138+
}

packages/vite-plugin-svelte/src/utils/options.ts

Lines changed: 23 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ const knownOptions = new Set([
1111
'extensions',
1212
'emitCss',
1313
'compilerOptions',
14+
'onwarn',
1415
'preprocess',
1516
'hot',
1617
'disableCssHmr',
@@ -180,7 +181,10 @@ export interface Options {
180181
/** Options passed to `svelte.compile` method. */
181182
compilerOptions: Partial<CompileOptions>;
182183

183-
onwarn?: undefined | false | ((warning: any, defaultHandler?: any) => void);
184+
/**
185+
* custom warning handler for svelte compiler warnings
186+
*/
187+
onwarn?: ((warning: Warning, defaultHandler?: (warning: Warning)=>void) => void);
184188

185189
/**
186190
* enable/disable hmr. You want this enabled.
@@ -392,3 +396,21 @@ export interface PreprocessorGroup {
392396
}
393397

394398
export type Arrayable<T> = T | T[];
399+
400+
export interface Warning {
401+
start?: {
402+
line: number;
403+
column: number;
404+
pos?: number;
405+
};
406+
end?: {
407+
line: number;
408+
column: number;
409+
};
410+
pos?: number;
411+
code: string;
412+
message: string;
413+
filename?: string;
414+
frame?: string;
415+
toString: () => string;
416+
}

0 commit comments

Comments
 (0)