From 1c430ab7fceeb7a89c67065efb422389218c9cf1 Mon Sep 17 00:00:00 2001 From: underfin Date: Tue, 12 Jan 2021 14:54:13 +0800 Subject: [PATCH] feat: error handling --- src/style.ts | 6 +++--- src/template.ts | 32 ++++++++++++++++++++++++++++---- src/utils/error.ts | 8 ++++++++ 3 files changed, 39 insertions(+), 7 deletions(-) create mode 100644 src/utils/error.ts diff --git a/src/style.ts b/src/style.ts index 4f30d3b..f637c01 100644 --- a/src/style.ts +++ b/src/style.ts @@ -22,9 +22,9 @@ export async function transformStyle( }) if (result.errors.length) { - result.errors.forEach((error: any) => { - pluginContext.error(error) - }) + result.errors.forEach((error) => + pluginContext.error({ id: filename, message: error }) + ) return null } diff --git a/src/template.ts b/src/template.ts index 46febe2..9417852 100644 --- a/src/template.ts +++ b/src/template.ts @@ -3,12 +3,13 @@ import * as vueTemplateCompiler from 'vue-template-compiler' import path from 'path' import { TransformPluginContext } from 'rollup' import { ResolvedOptions } from './index' +import { createRollupError } from './utils/error' export function compileSFCTemplate( source: string, block: SFCBlock, filename: string, - { root, isProduction, vueTemplateOptions, devServer }: ResolvedOptions, + { root, isProduction, vueTemplateOptions = {}, devServer }: ResolvedOptions, pluginContext: TransformPluginContext ): string { const { tips, errors, code } = compileTemplate({ @@ -29,12 +30,35 @@ export function compileSFCTemplate( }) if (tips) { - tips.forEach(console.warn) + tips.forEach((warn) => + pluginContext.error({ + id: filename, + message: typeof warn === 'string' ? warn : warn.msg, + }) + ) } - // todo if (errors) { - // errors.forEach((e) => pluginContext.error(e)) + errors.forEach((error) => { + // 2.6 compiler outputs errors as objects with range + if ( + vueTemplateCompiler.generateCodeFrame && + vueTemplateOptions.compilerOptions?.outputSourceRange + ) { + const { msg, start, end } = error as vueTemplateCompiler.ErrorWithRange + return pluginContext.error( + createRollupError(filename, { + message: msg, + frame: vueTemplateCompiler.generateCodeFrame(source, start, end), + }) + ) + } else { + pluginContext.error({ + id: filename, + message: typeof error === 'string' ? error : error.msg, + }) + } + }) } if (devServer) { diff --git a/src/utils/error.ts b/src/utils/error.ts new file mode 100644 index 0000000..cd4dff9 --- /dev/null +++ b/src/utils/error.ts @@ -0,0 +1,8 @@ +import { RollupError } from 'rollup' + +export function createRollupError(id: string, error: any): RollupError { + ;(error as RollupError).id = id + ;(error as RollupError).plugin = 'vite-plugin-vue2' + + return error as RollupError +}