Skip to content

Fix/compiler warnings #45

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

Merged
merged 6 commits into from
Jun 5, 2021
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/selfish-experts-rest.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@sveltejs/vite-plugin-svelte': patch
---

enable logging for compiler warnings
5 changes: 5 additions & 0 deletions .changeset/wise-impalas-glow.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@sveltejs/vite-plugin-svelte': minor
---

Feature: log svelte compiler warnings to console. use options.onwarn to customize logging
16 changes: 11 additions & 5 deletions packages/vite-plugin-svelte/src/handleHotUpdate.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { ModuleNode, HmrContext } from 'vite';
import { Code, CompileData } from './utils/compile';
import { log } from './utils/log';
import { log, logCompilerWarnings } from './utils/log';
import { SvelteRequest } from './utils/id';
import { VitePluginSvelteCache } from './utils/VitePluginSvelteCache';
import { ResolvedOptions } from './utils/options';
Expand All @@ -13,7 +13,7 @@ export async function handleHotUpdate(
ctx: HmrContext,
svelteRequest: SvelteRequest,
cache: VitePluginSvelteCache,
options: Partial<ResolvedOptions>
options: ResolvedOptions
): Promise<ModuleNode[] | void> {
const { read, server } = ctx;

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

const cssModule = server.moduleGraph.getModuleById(svelteRequest.cssId);
const mainModule = server.moduleGraph.getModuleById(svelteRequest.id);
if (cssModule && cssChanged(cachedCss, compileData.compiled.css)) {
const cssUpdated = cssModule && cssChanged(cachedCss, compileData.compiled.css);
if (cssUpdated) {
log.debug('handleHotUpdate css changed');
affectedModules.add(cssModule);
}

if (mainModule && jsChanged(cachedJS, compileData.compiled.js, svelteRequest.filename)) {
const jsUpdated = mainModule && jsChanged(cachedJS, compileData.compiled.js, svelteRequest.filename);
if (jsUpdated) {
log.debug('handleHotUpdate js changed');
affectedModules.add(mainModule);
}

if(!jsUpdated) {
// transform won't be called, log warnings here
logCompilerWarnings(compileData.compiled.warnings,options)
}

const result = [...affectedModules].filter(Boolean) as ModuleNode[];
log.debug(`handleHotUpdate result for ${svelteRequest.id}`, result);

Expand Down
9 changes: 4 additions & 5 deletions packages/vite-plugin-svelte/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,9 @@
import * as path from 'path';
import { HmrContext, IndexHtmlTransformContext, ModuleNode, Plugin, UserConfig } from 'vite';

// @ts-ignore
import * as relative from 'require-relative';

import { handleHotUpdate } from './handleHotUpdate';
import { log } from './utils/log';
import { log, logCompilerWarnings } from './utils/log';
import { CompileData, createCompileSvelte } from './utils/compile';
import { buildIdParser, IdParser, SvelteRequest } from './utils/id';
import {
Expand All @@ -29,7 +27,8 @@ export {
Arrayable,
MarkupPreprocessor,
ModuleFormat,
Processed
Processed,
Warning
} from './utils/options';

// extend the Vite plugin interface to be able to have `sveltePreprocess` injection
Expand Down Expand Up @@ -203,7 +202,7 @@ export default function vitePluginSvelte(inlineOptions?: Partial<Options>): Plug
throw new Error(`failed to transform tagged svelte request for id ${id}`);
}
const compileData = await compileSvelte(svelteRequest, code, options);

logCompilerWarnings(compileData.compiled.warnings, options);
cache.update(compileData);
if (compileData.dependencies?.length && options.server) {
compileData.dependencies.forEach((d) => this.addWatchFile(d));
Expand Down
9 changes: 1 addition & 8 deletions packages/vite-plugin-svelte/src/utils/compile.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ const _createCompileSvelte = (makeHot: Function) =>
options: Partial<ResolvedOptions>
): Promise<CompileData> {
const { filename, normalizedFilename, cssId, ssr } = svelteRequest;
const { onwarn, emitCss = true } = options;
const { emitCss = true } = options;
const dependencies = [];
const finalCompilerOptions: CompileOptions = {
...options.compilerOptions,
Expand All @@ -36,13 +36,6 @@ const _createCompileSvelte = (makeHot: Function) =>

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

(compiled.warnings || []).forEach((warning) => {
if (!emitCss && warning.code === 'css-unused-selector') return;
// TODO handle warnings
if (onwarn) onwarn(warning /*, this.warn*/);
//else this.warn(warning)
});

if (emitCss && compiled.css.code) {
// TODO properly update sourcemap?
compiled.js.code += `\nimport ${JSON.stringify(cssId)};\n`;
Expand Down
43 changes: 43 additions & 0 deletions packages/vite-plugin-svelte/src/utils/log.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
/* eslint-disable no-unused-vars */
import chalk from 'chalk';
import debug from 'debug';
import {ResolvedOptions, Warning} from "./options";

const levels: string[] = ['debug', 'info', 'warn', 'error', 'silent'];
const prefix = 'vite-plugin-svelte';
const loggers: { [key: string]: any } = {
Expand Down Expand Up @@ -93,3 +95,44 @@ export const log = {
// TODO still needed?
setViteLogOverwriteProtection
};


export function logCompilerWarnings(
warnings: Warning[],
options: ResolvedOptions
) {
const {emitCss,onwarn, isBuild} = options;
const warn = isBuild ? warnBuild : warnDev;
warnings?.forEach(warning => {
if (!emitCss && warning.code === 'css-unused-selector'){
return;
}
if (onwarn) {
onwarn(warning , warn);
} else {
warn(warning)
}
})
}

function warnDev(w: Warning) {
log.info.enabled && log.info(buildExtendedLogMessage(w))
}

function warnBuild(w: Warning) {
log.warn.enabled && log.warn(buildExtendedLogMessage(w),w.frame)
}

function buildExtendedLogMessage(w: Warning) {
const parts = [];
if(w.filename) {
parts.push(w.filename)
}
if(w.start) {
parts.push(':',w.start.line,':',w.start.column)
}
if(w.message){
parts.push(' ',w.message)
}
return parts.join('');
}
24 changes: 23 additions & 1 deletion packages/vite-plugin-svelte/src/utils/options.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ const knownOptions = new Set([
'extensions',
'emitCss',
'compilerOptions',
'onwarn',
'preprocess',
'hot',
'disableCssHmr',
Expand Down Expand Up @@ -180,7 +181,10 @@ export interface Options {
/** Options passed to `svelte.compile` method. */
compilerOptions: Partial<CompileOptions>;

onwarn?: undefined | false | ((warning: any, defaultHandler?: any) => void);
/**
* custom warning handler for svelte compiler warnings
*/
onwarn?: ((warning: Warning, defaultHandler?: (warning: Warning)=>void) => void);

/**
* enable/disable hmr. You want this enabled.
Expand Down Expand Up @@ -392,3 +396,21 @@ export interface PreprocessorGroup {
}

export type Arrayable<T> = T | T[];

export interface Warning {
start?: {
line: number;
column: number;
pos?: number;
};
end?: {
line: number;
column: number;
};
pos?: number;
code: string;
message: string;
filename?: string;
frame?: string;
toString: () => string;
}