menu 刘兴刚博客
more_vert
chevron_right 首页 » WEB开发 » 正文
hexo性能优化补充
2016-12-08 | WEB开发 | 暂无评论 | 9766 次阅读 | 191字

升级gulp4.0后似乎感觉出网站打开速度快那么一点点了,也许就是心理幻想吧!<!--more-->

使用构建工具对静态资源进行压缩优化

gulp 4.0 即将发布, 现在已经可以开始使用.gulp 4.0的变化可以参考这篇博文

  • 安装:
npm uninstall -g gulp
npm i -g gulp-cli
npm i --save-dev autoprefixer del gulpjs/gulp-cli#4.0 gulp-load-plugins gulp-postcss gulp-posthtml gulp-uglify gulp-xml postcss-clean posthtml-minifier posthtml-postcss

由于已经安装过gulp 3.9所以的按以下操作

# 如果安装过全局的 gulp 的话先卸载之
$ npm uninstall gulp -g

# 安装全局的 gulp 4.0
$ npm install "gulpjs/gulp#4.0" -g

# 到项目目录里删掉本地的 gulp
$ npm rm gulp --save-dev

# 安装本地的 gulp 4.0
$ npm install "gulpjs/gulp#4.0" --save-dev
  • 配置(gulpfile.js):
const gulp = require('gulp'),
    postcss = require('posthtml-postcss'),
    htmlmin = require('posthtml-minifier'),
    autoprefixer = require('autoprefixer'),
    cleancss = require('postcss-clean'),
    $ = require('gulp-load-plugins')(),
    del = require('del');
const app = {
        build: 'build'
    },
    base = 'public/**/*.';
['css', 'js'].forEach(function (value) {
    app[value] = [`${base + value}`, `!${base}min.${value}`];
});
['html', 'xml'].forEach(function (value) {
    app[value] = `${base + value}`;
});
function clean() {
    return del(app.build);
}
function css() {
    return gulp.src(app.css)
        .pipe($.postcss([
            autoprefixer(),
            cleancss()]))
        .pipe(gulp.dest(app.build));
}
function js() {
    return gulp.src(app.js)
        .pipe($.uglify())
        .pipe(gulp.dest(app.build));
}
function html() {
    return gulp.src(app.html)
        .pipe($.posthtml([
            postcss([autoprefixer, cleancss]),
            htmlmin({
                collapseBooleanAttributes: true,
                collapseWhitespace: true,
                minifyCSS: true,
                minifyJS: true,
                removeTagWhitespace: true
            })
        ]))
        .pipe(gulp.dest(app.build));
}
function xml() {
    return gulp.src(app.xml)
        .pipe($.xml({
            parseOpts: {
                trim: true
            },
            buildOpts: {
                renderOpts: {
                    pretty: false
                },
                allowSurrogateChars: true,
                cdata: true
            },
            callback: function (result) {
                return result.replace(/\s{2,}/g, ' ');
            }
        }))
        .pipe(gulp.dest(app.build));
}
gulp.task(clean);
gulp.task('default', gulp.series(
    clean,    //这个是清楚public目录后生成第9行设置的新的文件夹名,我删除了这个,同时把第9行的生成目录名设置为了public
    gulp.parallel(css, js, html, xml)
));

PS: gulp-xml 是为了处理压缩 search.xml 和 sitemap.xml 等 .xml 文件而使用 node-xml2js 编写的 gulp 插件, 欢迎使用.

发表评论
暂无评论
textsms
account_circle
email
link
arrow_back 上一篇
arrow_forward 下一篇
""