From 62b9d02f6fbb08d51bed73f33435c1ed83d5b2ea Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Barth=C3=A9l=C3=A9my=20Ledoux?= Date: Mon, 17 Aug 2020 10:20:28 -0500 Subject: [PATCH] feat(compiler-core): add `comments` parser option (#1858) --- packages/compiler-core/__tests__/parse.spec.ts | 10 ++++++++++ packages/compiler-core/src/options.ts | 4 ++++ packages/compiler-core/src/parse.ts | 11 ++++++++--- 3 files changed, 22 insertions(+), 3 deletions(-) diff --git a/packages/compiler-core/__tests__/parse.spec.ts b/packages/compiler-core/__tests__/parse.spec.ts index 7f12a700..56bea060 100644 --- a/packages/compiler-core/__tests__/parse.spec.ts +++ b/packages/compiler-core/__tests__/parse.spec.ts @@ -374,6 +374,16 @@ describe('compiler: parse', () => { } }) }) + + test('comments option', () => { + __DEV__ = false + const astNoComment = baseParse('') + const astWithComments = baseParse('', { comments: true }) + __DEV__ = true + + expect(astNoComment.children).toHaveLength(0) + expect(astWithComments.children).toHaveLength(1) + }) }) describe('Element', () => { diff --git a/packages/compiler-core/src/options.ts b/packages/compiler-core/src/options.ts index f0d5258c..22d8a086 100644 --- a/packages/compiler-core/src/options.ts +++ b/packages/compiler-core/src/options.ts @@ -49,6 +49,10 @@ export interface ParserOptions { */ decodeEntities?: (rawText: string, asAttr: boolean) => string onError?: (error: CompilerError) => void + /** + * Keep comments in the templates AST, even in production + */ + comments?: boolean } export type HoistTransform = ( diff --git a/packages/compiler-core/src/parse.ts b/packages/compiler-core/src/parse.ts index e2888e32..60d60427 100644 --- a/packages/compiler-core/src/parse.ts +++ b/packages/compiler-core/src/parse.ts @@ -50,7 +50,8 @@ export const defaultParserOptions: MergedParserOptions = { isCustomElement: NO, decodeEntities: (rawText: string): string => rawText.replace(decodeRE, (_, p1) => decodeMap[p1]), - onError: defaultOnError + onError: defaultOnError, + comments: false } export const enum TextModes { @@ -228,8 +229,12 @@ function parseChildren( } else { node.content = node.content.replace(/[\t\r\n\f ]+/g, ' ') } - } else if (!__DEV__ && node.type === NodeTypes.COMMENT) { - // remove comment nodes in prod + } else if ( + !__DEV__ && + node.type === NodeTypes.COMMENT && + !context.options.comments + ) { + // remove comment nodes in prod by default removedWhitespace = true nodes[i] = null as any }