feat(compiler-core): add comments parser option (#1858)

This commit is contained in:
Barthélémy Ledoux 2020-08-17 10:20:28 -05:00 committed by GitHub
parent 823a2bc563
commit 62b9d02f6f
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 22 additions and 3 deletions

View File

@ -374,6 +374,16 @@ describe('compiler: parse', () => {
} }
}) })
}) })
test('comments option', () => {
__DEV__ = false
const astNoComment = baseParse('<!--abc-->')
const astWithComments = baseParse('<!--abc-->', { comments: true })
__DEV__ = true
expect(astNoComment.children).toHaveLength(0)
expect(astWithComments.children).toHaveLength(1)
})
}) })
describe('Element', () => { describe('Element', () => {

View File

@ -49,6 +49,10 @@ export interface ParserOptions {
*/ */
decodeEntities?: (rawText: string, asAttr: boolean) => string decodeEntities?: (rawText: string, asAttr: boolean) => string
onError?: (error: CompilerError) => void onError?: (error: CompilerError) => void
/**
* Keep comments in the templates AST, even in production
*/
comments?: boolean
} }
export type HoistTransform = ( export type HoistTransform = (

View File

@ -50,7 +50,8 @@ export const defaultParserOptions: MergedParserOptions = {
isCustomElement: NO, isCustomElement: NO,
decodeEntities: (rawText: string): string => decodeEntities: (rawText: string): string =>
rawText.replace(decodeRE, (_, p1) => decodeMap[p1]), rawText.replace(decodeRE, (_, p1) => decodeMap[p1]),
onError: defaultOnError onError: defaultOnError,
comments: false
} }
export const enum TextModes { export const enum TextModes {
@ -228,8 +229,12 @@ function parseChildren(
} else { } else {
node.content = node.content.replace(/[\t\r\n\f ]+/g, ' ') node.content = node.content.replace(/[\t\r\n\f ]+/g, ' ')
} }
} else if (!__DEV__ && node.type === NodeTypes.COMMENT) { } else if (
// remove comment nodes in prod !__DEV__ &&
node.type === NodeTypes.COMMENT &&
!context.options.comments
) {
// remove comment nodes in prod by default
removedWhitespace = true removedWhitespace = true
nodes[i] = null as any nodes[i] = null as any
} }