首页 > gulp分组合并(gulp-group-concat)后如何替换html中的引用?

gulp分组合并(gulp-group-concat)后如何替换html中的引用?

现在需要对一个老的前端项目使用gulp进行合并打包等工作,
因为页面以及JS/CSS文件都很多,所以想使用gulp-group-concat进行分组合并后再根据mapping关系去替换原HTML中的引用,比如plugins/a.jsplugins/b.jsplugins/b.js合并为了plugins/abc.js, 则将HTML中所有引用到这三个文件的地方替换为abc.js(同时还要去重)

请问是否有插件能够实现以上需求?或者是否有更好的方案?

update =======
有两位朋友提到了gulp-useref和gulp-usemin,这两个插件之前也看过,感觉不是特别适用(也可能是我对用法还不够了解)。
我的理解是,这两个插件都是通过在html中写注释的方式定义我要怎么去合并js文件
但是,由于我在多个页面可能引用类似的js文件,
比如在index.html中引用了a.js, b.js, c.js,而demo.html中引用了a.js, b.js,我现在希望将a.js, b.js, c.js合并为abc.js,并同时对index.htmldemo.html中的引用进行替换,替换后index.htmldemo.html都只需要引用abc.js即可
这种场景不知道要怎么处理?

https://github.com/jonkemp/gulp-useref/issues/140
这个gulp-useref的issue跟我的问题类似,目前也尚未解决


发现一个插件应该适用你这种情况: https://github.com/cgross/gulp-dom-src
贴一段官方的代码片段给你:

var gulp = require('gulp');
var domSrc = require('gulp-dom-src');
var concat = require('gulp-concat');
var cssmin = require('gulp-cssmin');
var uglify = require('gulp-uglify');
var cheerio = require('gulp-cheerio');

gulp.task('css', function() {
    return domSrc({file:'index.html',selector:'link',attribute:'href'})
        .pipe(concat('app.full.min.css'))
        .pipe(cssmin())
        .pipe(gulp.dest('dist/'));
});

gulp.task('js', function() {
    return domSrc({file:'index.html',selector:'script',attribute:'src'})
        .pipe(concat('app.full.min.js'))
        .pipe(uglify())
        .pipe(gulp.dest('dist/'));
});

gulp.task('indexHtml', function() {
    return gulp.src('index.html')
        .pipe(cheerio(function ($) {
            $('script').remove();
            $('link').remove();
            $('body').append('<script src="app.full.min.js"></script>');
            $('head').append('<link rel="stylesheet" href="app.full.min.css">');
        }))
        .pipe(gulp.dest('dist/'));
});

顺便分享一下我们team的use-gulp项目 https://github.com/Platform-CUF/use-gulp


这是我建的一个gulp-template
用了gulp-usemin、gulp-rev,
可以合并css和js并自动更换路径和添加版本号
https://github.com/hxbo/gulp-project-template


gulp-useref

https://www.npmjs.com/package/gulp-useref


gulp-usemin插件,你可能还需要gulp-rev
可以看看这个地址:https://www.npmjs.com/package/gulp-usemin

【热门文章】
【热门文章】