pwa.js 2.91 KB
const { resolve } = require("path");
const gulp = require('gulp');
const replace = require("gulp-replace");
const pump = require("pump");
const uglify = require("gulp-uglify");
const rev = require("gulp-rev");

const util = require("../common/util");
const { DEFAULT_REL_BUILD_TASK } = require("../common/constants");

const precache = {
    js: [
        "require",
        "main"
    ],
    css: [

    ]
};

module.exports = (baseUrl, mainoutput) => {
    const TASK_PRECACHE = "pwa-precache";
    const _pwa = {
        version: "",
        precache: (getMd5Mapping, getPaths) => {
            gulp.task(TASK_PRECACHE, [DEFAULT_REL_BUILD_TASK], cb => {
                const swPath = `${baseUrl}/js/cacheManager/sw.js`;
                const paths = getPaths();
                const md5Mapping = getMd5Mapping();

                pump([
                    gulp.src(swPath),
                    replace(/precache: \[([\s\S]*?)\]/g, () => {
                        let cache = [];
                        const fmt = (mod, type) => `'./dist/${paths[mod]}.${type}?v=${md5Mapping[mod]}'`;

                        cache = cache.concat(precache.js.map(mod => fmt(mod, "js")));
                        cache = cache.concat(precache.css.map(mod => fmt(mod, "css")));

                        return `precache: [${cache.join(",")}]`;
                    }),
                    uglify(),
                    gulp.dest(baseUrl),
                    rev(),
                    rev.manifest(),
                    replace(/^{[.\s\S]*}$/, match => {
                        let o = JSON.parse(match);

                        _pwa.version = util.getMd5( o["sw.js"]);

                        return match;
                    }),
                ], cb);
            });
            return TASK_PRECACHE;
        },
        changeVersion:  () => {
            const TASK_CHANGE_VERSION = "pwa-change-version";

            gulp.task(TASK_CHANGE_VERSION, [TASK_PRECACHE], cb => {
                pump([
                    gulp.src(`${mainoutput.js}/loader.js`),
                    replace(/sw\.js\?v=\w*?"/g, match => {
                        match = match.replace(/v=(\w)*?"/, `v=${_pwa.version}"`);

                        return match;
                    }),
                    gulp.dest(mainoutput.js),
                    gulp.src(`${baseUrl}/js/loader.js`),
                    replace(/sw\.js\?v=\w*?"/g, match => {
                        match = match.replace(/v=(\w)*?"/, `v=${_pwa.version}"`);

                        return match;
                    }),
                    gulp.dest(`${baseUrl}/js`)
                ], cb)
            });

            return TASK_CHANGE_VERSION;
        }
    };

    return {
        regsiter: settings => {
            let { precache, changeVersion } = _pwa;
            const { getMd5Mapping, getPaths } = settings;

            gulp.task("pwa", [precache(getMd5Mapping, getPaths), changeVersion(getMd5Mapping)]);
        }
    };
};