如何使用Gulp移除HTML文件中的Sourcemap注释
问题:移除Gulp处理后HTML文件中的Sourcemap注释
我将CSS文件副本的扩展名从.css改为.html,并用<style>标签包裹CSS规则,得到page-css.html文件,内容如下:
<style> html body { border: solid 1rem blue; } html body .form-row { margin-bottom: 15px; } /*# sourceMappingURL=data:application/json;charset=utf8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbInBhZ2UtY3NzLnNjc3MiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IkFBQ0k7RUFDSTs7QUFFQTtFQUNJIiwiZmlsZSI6InBhZ2UtY3NzLmNzcyIsInNvdXJjZXNDb250ZW50IjpbImh0bWwge1xyXG4gICAgYm9keSB7XHJcbiAgICAgICAgYm9yZGVyOiBzb2xpZCAxcmVtIGJsdWU7XHJcblxyXG4gICAgICAgIC5mb3JtLXJvdyB7XHJcbiAgICAgICAgICAgIG1hcmdpbi1ib3R0b206IDE1cHg7XHJcbiAgICAgICAgfVxyXG4gICAgfVxyXG59Il19 */ </style>
我需要移除该文件中的整个Sourcemap注释,但尝试gulp-decomment、gulp-string-replace、gulp-strip-comments等插件,以及以下配置均无效:
const htmlmin = require('gulp-htmlmin'); const decomment = require('gulp-decomment'); const replace = require('gulp-string-replace'); const strip = require('gulp-strip-comments'); ... //example 1 .pipe(decomment({trim: true})) //example 2 .pipe(htmlmin({ removeComments: true })) //example 3 .pipe(strip())
完整Gulp代码示例
function genCSS(done) { return ( src(paths.styles.src) .pipe(gulpif(!GPREP, sourcemaps.init({}))) .pipe(sass().on("error", sass.logError)) .pipe( gulpif( !GPREP, sourcemaps.write({ addComment: true, }) ) ) //CSS FILE WITH ITS SOURCEMAP IS READY FOR LOCAL DEV PURPOSES .pipe(dest(paths.styles.dest)) //BEGIN THE COPIED/CONVERTED HTML FILE FOR GOOGLE APP PURPOSES .pipe( rename(function (path) { if (path.basename === "page-css") { path.extname = ".html"; } }) ) .pipe(header("<style>\n")) .pipe(footer("</style>\n")) //ATTEMPTING TO REMOVE THE SOURCEMAP - BUT IT DOES NOT WORK... .pipe(greplace(/\/\*# sourceMappingURL[^\n]+\n/gm,'')) //STORE THE FILE IN A CLASP LOCATION TO PUSH UP TO GOOGLE .pipe(dest(paths.styles.apps)) .pipe(msync.stream()) ); done(); }
可行解决方案
方案1:修正gulp-replace的正则表达式
原正则未匹配到注释结尾的*/,且未考虑注释前后的空白字符。替换为以下正则,确保完整匹配Sourcemap注释块:
.pipe(greplace(/\/\*# sourceMappingURL[\s\S]*?\*\//g, ''))
说明:
\/\*# sourceMappingURL:精准匹配Sourcemap注释的开头[\s\S]*?:匹配任意字符(含换行),非贪婪模式避免误匹配其他内容\*\/:匹配注释的结尾
方案2:拆分流,避免HTML分支生成Sourcemap
将本地开发用CSS和Google App用HTML的生成流程拆分,HTML分支不生成Sourcemap注释,从根源避免问题:
function genCSS(done) { // 处理本地开发用CSS(带Sourcemap) src(paths.styles.src) .pipe(gulpif(!GPREP, sourcemaps.init({}))) .pipe(sass().on("error", sass.logError)) .pipe(gulpif(!GPREP, sourcemaps.write({ addComment: true }))) .pipe(dest(paths.styles.dest)); // 处理Google App用HTML(无Sourcemap) src(paths.styles.src) .pipe(sass().on("error", sass.logError)) .pipe(rename(function (path) { if (path.basename === "page-css") { path.extname = ".html"; } })) .pipe(header("<style>\n")) .pipe(footer("</style>\n")) .pipe(dest(paths.styles.apps)) .pipe(msync.stream()); done(); }
这种方式无需后续移除操作,直接生成符合需求的HTML文件。
内容的提问来源于stack exchange,提问作者klewis
相关产品推荐
相关产品推荐

