解决uglify压缩模板字符串时多余换行和空格问题
上图显示了Uglify压缩模板字符串后,残留了多余的换行符和空格。 以下方法可以有效去除这些多余字符:
方法一: 使用美化工具 (beautifier)
此方法结合了UglifyJS和JS Beautify库。先用UglifyJS压缩代码,再用JS Beautify格式化,并去除换行和空格。
<code class="javascript">const uglify = require('uglify-js');
const beautify = require('js-beautify');
const code = `
<p>
this is a template string
with multiple lines and spaces.
</p>
`;
const compressed = uglify.minify(code).code;
const formatted = beautify.html(compressed, {
wrap_line_length: 0, // 禁用换行
preserve_newlines: false, // 去除换行
});
console.log(formatted); // 输出: <p>this is a template string with multiple lines and spaces.</p></code>
方法二: 使用正则表达式
利用正则表达式直接替换换行符和空格。
<code class="javascript">const code = `
<p>
this is a template string
with multiple lines and spaces.
</p>
`;
const regex = /\r?\n|\s+/g; // 匹配所有换行符和多个空格
const compressed = code.replace(regex, '');
console.log(compressed); // 输出: <p>this is a template stringwith multiple lines and spaces.</p></code>
方法三: 使用Lodash的compact方法
Lodash库的compact方法可以去除数组中的空元素。此方法先将字符串按行分割成数组,去除空行,再连接成字符串。
<code class="javascript">const _ = require('lodash'); // 需要安装lodash库
const code = `
<p>
This is a template string
with multiple lines and spaces.
</p>
`;
const compressed = _.compact(code.split('\n')).join('');
console.log(compressed); // 输出: <p>This is a template stringwith multiple lines and spaces.</p></code>
注意: 方法二和方法三在去除空格方面略有不同。方法二会去除所有空格,而方法三只去除行首行尾的空格。选择哪种方法取决于你的具体需求。 方法一通常是最佳选择,因为它提供了更好的控制和更可靠的结果。 记住安装必要的库:npm install uglify-js js-beautify lodash











