var css = `
.test {
background-image: url(//www.google.com/image/1.png); // goole iamge
}
@font-face {
font-display: auto;
font-family: vant-icon;
font-style: normal;
font-weight: 400;
src: url(https://at.alicdn.com/t/c/font_2553510_kfwma2yq1rs.woff2?t=1694918397022)
format("woff2"),
url("https://at.alicdn.com/t/c/font_2553510_kfwma2yq1rs.woff?t=1694918397022")
format("woff");
}
/**
I‘am commonts
*/
`
上面的代码我想删除所有注释。但这太难了,因为代码有像
https://
,url(//xxx)
这样的键盘。如何解决这个问题?
这是错误的方式
var re2 = /\/\*[\s\S]*?\*\/|(?<=[^:])\/\/.*|^\/\/.*/g; // incorrect
// this code is incorrect
期待
CSS代码
.test {
background-image: url(//www.google.com/image/1.png);
}
@font-face {
font-display: auto;
font-family: vant-icon;
font-style: normal;
font-weight: 400;
src: url(https://at.alicdn.com/t/c/font_2553510_kfwma2yq1rs.woff2?t=1694918397022)
format("woff2"),
url("https://at.alicdn.com/t/c/font_2553510_kfwma2yq1rs.woff?t=1694918397022")
format("woff");
}
此代码是正确的。
clean-css
可以用,但是如何使用简单的方法呢?
您可以使用 DOM,但不会保留格式:
var css = `
.test {
background-image: url(//www.google.com/image/1.png); // goole iamge
}
@font-face {
font-display: auto;
font-family: vant-icon;
font-style: normal;
font-weight: 400;
src: url(https://at.alicdn.com/t/c/font_2553510_kfwma2yq1rs.woff2?t=1694918397022)
format("woff2"),
url("https://at.alicdn.com/t/c/font_2553510_kfwma2yq1rs.woff?t=1694918397022")
format("woff");
}
/**
I‘am commonts
*/
`;
const sheet = new CSSStyleSheet;
sheet.replaceSync(css);
const filtered = [...sheet.rules].map(r => r.cssText).join('');
console.log(filtered.replaceAll(/[{};]/g, '$&\n'));
如果您想删除有效的CSS注释并保留格式,您可以使用此正则表达式:
const css = `.test {
background-image: url(//www.google.com/image/1.png);
}
@font-face {
font-display: auto;
font-family: vant-icon;
font-style: normal;
font-weight: 400;
src: url(https://at.alicdn.com/t/c/font_2553510_kfwma2yq1rs.woff2?t=1694918397022)
format("woff2"),
url("https://at.alicdn.com/t/c/font_2553510_kfwma2yq1rs.woff?t=1694918397022")
format("woff");
}
/**
Some comment
*/ body {
color: /* some nice
color */ gold;
}`;
console.log(css.replace(/\/\*.*?\*\//gsm, ""));
如果您还想删除一些单行注释,例如
// Some comment
,这将使其更像 SCSS 语法,您可以使用(未经测试):
const css = `.test {
background-image: url(//www.google.com/image/1.png); // goole iamge
}
@font-face {
font-display: auto;
font-family: vant-icon; ////// blah!!!
font-style: normal;
font-weight: 400;
src: url(https://at.alicdn.com/t/c/font_2553510_kfwma2yq1rs.woff2?t=1694918397022)
format("woff2"),
url("https://at.alicdn.com/t/c/font_2553510_kfwma2yq1rs.woff?t=1694918397022")
format("woff");
}
/**
Some comment
*/ body {
color: /* some nice
color */ gold;
}`;
console.log(css.replace(/\/\*.*?\*\/|\/+[^/)]*?$/gsm, ""));