Skip to content

Trim whitespaces from texts in vue-template-compiler output #3934

Closed
@SebastianS90

Description

@SebastianS90

I love the feature of single file components. They allow for proper syntax highlighting and we can write HTML without putting everything in awkward javascript strings.
A proper indentation within the template is useful to improve readability of .vue files.

Consider this example:

<template>
  <div>
    <p>
      This is my first text
    </p>
    <p>
      This is my second text
    </p>
  </div>
</template>

Compile it with webpack. The resulting bundle contains a compiled version of the template, you will find the following line:

return _h('div', [_h('p', ["\n    This is my first text\n  "]), " ", _h('p', ["\n    This is my second text\n  "])])

There is this preserveWhitespace option described here. If you configure webpack with loader: 'vue?preserveWhitespace=false', then you get the following:

return _h('div', [_h('p', ["\n    This is my first text\n  "]), _h('p', ["\n    This is my second text\n  "])])

Note that one array entry " " has gone, i.e. the whitespace between </p> and <p> has been removed.
But how about the leading and trailing whitespaces in the string "\n This is my first text\n " ?

My Feature Rrequest

Allow to trim these texts. The compilation result should look like this:

return _h('div', [_h('p', ["This is my first text"]), _h('p', ["This is my second text"])])

Changing this line as follows achieves what I want:

       text = inPre || text.trim()
-        ? decodeHTMLCached(text)
+        ? decodeHTMLCached(inPre || preserveWhitespace ? text : text.trim())
         // only preserve whitespace if its not right after a starting tag
         : preserveWhitespace && currentParent.children.length ? ' ' : '';

But I do not know whether it might break more complex layouts, so I posted it as issue here for discussion.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions