xinglie / xinglie.github.io

blog
https://xinglie.github.io
153 stars 22 forks source link

模板属性中变量拼接策略 #105

Open xinglie opened 1 year ago

xinglie commented 1 year ago

假设我们需要在html的元素节点上添加样式,考虑以下代码

<div class="a b {{if e}} d{{/if}} c">

</div>

以及

<div class="a b c {{if e}} d{{/if}}">

</div>

class中最终的结果都是应用a b c d样式。

但是2种写法产生的代码字节数是不一样的。

第一种会产生

let $class=`a b`;
if(e)$class+=' d';
$class+=' c';

第二种会生产

let $class=`a b c`;
if(e)$class+=' d';

我们可以看到第二种更少的字节数和更高的拼接效率

目前magix-composer无法智能的去纠正这个问题,但会抛出警告,提示开发者改变位置,向magix-composer提供更优的输入,以产出最少的代码字节输出。

不要把可变部分放在属性的中间