用正则表达式替换混合 HTML 和 JavaScript 的文件中的注释是有风险的。然而,单独地,你可以在不依赖外部工具的情况下获得良好的性能,只需要node.js:
对于 HTML 注释,请使用正则表达式/<!--(?!>)[\S\s]*?-->/g
。例子:
function stripHtmlComments(content) {
return content.replace(/<!--(?!>)[\S\s]*?-->/g, '');
}
删除 JavaScript 注释有点复杂,您需要混合多个正则表达式来区分注释何时位于文字字符串或正则表达式中,以及斜杠何时属于正则表达式:)
这个小程序从 JavaScript 文件中删除多行和单行注释:
#!/usr/bin/env node
/*
Removes multiline and single-line comments from a JavaScript source file.
Author: aMarCruz - https://github.com/aMarCruz
Usage: node [this-tool] [js-file]
*/
var path = require('path'),
fs = require('fs'),
file,
str;
var RE_BLOCKS = new RegExp([
/\/(\*)[^*]*\*+(?:[^*\/][^*]*\*+)*\//.source, // $1: multi-line comment
/\/(\/)[^\n]*$/.source, // $2 single-line comment
/"(?:[^"\\]*|\\[\S\s])*"|'(?:[^'\\]*|\\[\S\s])*'/.source, // string, don't care about embedded eols
/(?:[$\w\)\]]|\+\+|--)\s*\/(?![*\/])/.source, // division operator
/\/(?=[^*\/])[^[/\\]*(?:(?:\[(?:\\.|[^\]\\]*)*\]|\\.)[^[/\\]*)*?\/[gim]*/.source
].join('|'), // regex
'gm' // note: global+multiline with replace() need test
);
file = process.argv[2];
if (!path.extname(file))
file += '.js';
str = fs.readFileSync(file, { encoding: 'utf8' });
console.log(stripJSComments(str));
// remove comments, keep other blocks
function stripJSComments(str) {
return str.replace(RE_BLOCKS, function (match, mlc, slc) {
return mlc ? ' ' : // multiline comment (must be replaced with one space)
slc ? '' : // single-line comment
match; // divisor, regex, or string, return as-is
});
}
现在(示例)另存为rcomms
并运行:
node rcomms source-file > clean-file.js
NOTE:此代码基于 jspreproc 的正则表达式,如果您需要更高级的处理,请访问http://github.com/aMarCruz/jspreproc http://github.com/aMarCruz/jspreproc.
I wrote jspreproc http://github.com/aMarCruz/jspreproc部署一些riot http://github.com/riot/riot模块。
jspreproc 删除空行,支持过滤器以保留一些注释和有条件的评论C 风格:#if-else、endif、#define、#include 等。