mask2012 / MaskBlog

all blogs are in issues.
12 stars 5 forks source link

gulp之把css,script,image全部合并到一个html #68

Open mask2012 opened 5 years ago

mask2012 commented 5 years ago

接到需求说要把所有资源都转到一个html中,于是折腾半天搞出来, 用到了gulp-file-inline发现非常好用 首先是clean清理目录 然后是用到了gulp-base64把css文件里用到的图片转成base64 最后一步是通过gulp-file-inline把所有资源统统弄进html

这里有个需要优化的点就是,我在gulp-base64这一步时,是直接覆盖了原css文件的,以后再修改css就会有点麻烦,正确的做法是dist设到release目录下的一个临时目录,然后把css,js,html文件也搬到临时目录,然后gulp-file-inline的时候从临时目录开始生成,这样就不会影响到源文件了。

var gulp = require('gulp');
var clean = require("gulp-clean"); //清理目录
var fs = require('fs');
var mime = require('mime');
var fileInline = require('gulp-file-inline');
var base64 = require('gulp-base64');

var inlineOptions = {
    htmlList: [
        "./public/exchangePlatform/index.html",
    ],
    cssList:[
        "./public/exchangePlatform/css/*.css",
    ],
    cssDest: './public/exchangePlatform/css/',
    htmlDest: './public/exchangePlatform/release/'
};

//强制清空目录
gulp.task("clean", function () {
    return gulp.src([inlineOptions.htmlDest], {
        read: false,
        allowEmpty: true
    })
        .pipe(clean({ force: true }));
});

//将css里的图片转成base64,5000k大小以内的生效
gulp.task('sourceBase64', function () {
    return gulp.src(inlineOptions.cssList,{allowEmpty:true})
        .pipe(base64({
            baseDir: inlineOptions.cssDest,
            extensions: ['png',, 'jpg', 'gif'],
            maxImageSize: 5000*1024, // bytes
            debug: true
        }))
        .pipe(gulp.dest(inlineOptions.cssDest));
});

//所有css,script,image插入一个html
gulp.task('inlinePages', function () {
    return gulp.src(inlineOptions.htmlList,{allowEmpty:true})
        .pipe(fileInline({
            img: {
                tagPattern: /<img[^>]* src=[^>]+>/g,
                urlPattern: / src=['"]?([^'"]+)['"]?/,
                tagParser: function (codes, attrCodes) {
                    return '<img' + attrCodes + ' src="' + codes + '">';
                },
                parser: function (base, filename, encoding, minify) {
                    var content = fs.readFileSync(filename).toString('base64');
                    var contentType = mime.getType(filename);
                    return 'data:' + contentType + ';base64,' + content;
                }
            }
        }))
        .pipe(gulp.dest(inlineOptions.htmlDest));
});

gulp.task('toOneFile', gulp.series(
    'clean',
    'sourceBase64',
    gulp.parallel(['inlinePages'])
));