Trim whitespaces from texts in vue-template-compiler output
See original GitHub issueI 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.
Issue Analytics
- State:
- Created 7 years ago
- Reactions:10
- Comments:15 (4 by maintainers)
Top GitHub Comments
@yyx990803 Hey Evan. Just to follow up on this issue: we find lots of pieces like this in our generated code:
We have thousands of those in our project, so they add up to quite some kBs. Compression should take care of them quite easily, but never the less it’s just not nice to have this in the generated output when we could simply remove them during compile-time.
I’ll see if I can add an option to the template compiler myself and will give you a pull request if I succeed. I’m thinking of something like
purgeWhitespace: ['div', 'span', ...]
FYI I don’t think this is a good idea, in the sense that it could be “unsafe” - the user may want to ignore whitespaces between tags, but not necessarily trimming all plain text, e.g inside
<pre>
. Whitespace between tags and whitespace around plain text are different in this sense.On the other hand I don’t see practical advantage for this. Ignoring additional whitespace nodes has a small perf gain, but trimming text doesn’t do much in that aspect.