Last active
February 15, 2017 04:55
-
-
Save azzgo/168b8fbc0fe025c49e69dc29e52ec0c0 to your computer and use it in GitHub Desktop.
UserefPlugin
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var useref = require('useref'); | |
var { keys } = require('lodash'); | |
var gulp = require('gulp'); | |
var concat = require('gulp-concat'); | |
var nano = require('gulp-cssnano'); | |
var uglify = require('gulp-uglify'); | |
var runSequence = require('run-sequence'); | |
var path = require('path'); | |
var helpers = require('./helpers') | |
function UserefPlugin() { | |
} | |
UserefPlugin.prototype.apply = function (compiler) { | |
compiler.plugin('compilation', function (compilation) { | |
compilation.plugin('html-webpack-plugin-before-html-processing', function (htmlPluginData, callback) { | |
console.log('The compiler is starting a new compilation in UserefPlugin...'); | |
var result = useref(htmlPluginData.html); | |
var templatePath = htmlPluginData.plugin.options.template.split('!').pop() | |
var base = `${path.dirname(templatePath)}/`; | |
var destPath = helpers.root(compilation.compiler.outputPath); | |
htmlPluginData.html = result[0]; | |
var cssKeyArrays = keys(result[1].css); | |
var jsKeyArrays = keys(result[1].js); | |
cssKeyArrays.forEach(key => { | |
gulp.task(key, function() { | |
return gulp.src( | |
result[1].css[key]['assets'].map(item => base + item), | |
{ base: base } | |
) | |
.pipe(concat(key)) | |
.pipe(nano()) | |
.pipe(gulp.dest(destPath)) | |
}) | |
}) | |
jsKeyArrays.forEach(key => { | |
gulp.task(key, function() { | |
return gulp.src( | |
result[1].js[key]['assets'].map(item => base + item), | |
{ base: base } | |
) | |
.pipe(concat(key)) | |
.pipe(uglify()) | |
.pipe(gulp.dest(destPath)) | |
}) | |
}) | |
runSequence(cssKeyArrays, jsKeyArrays, function() { | |
callback(null, htmlPluginData); | |
}); | |
}); | |
}); | |
} | |
module.exports = UserefPlugin; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment