Gulp Inject css and js file in html page

Once we are done with javascript/css minify we need to update our html page to link to new build assets. There are some gulp tools available for that. Here we will also update the version for each assets after each deployment

var gulp = require('gulp'),
    inject = require('gulp-inject'),
    time = (new Date()).getTime();

var transform = function (filepath) {
		arguments[0] = filepath + '?v=' + time;
	return inject.transform.apply(inject.transform, arguments);

Below is the gulp task to inject css and js files

	var	target = gulp.src('./src/index.html'),
		cssfile = `${__dirname}/build/css/style.min.css`,
		jsfile = `${__dirname}/build/static.min.js`,
		libjsfile = `${__dirname}/build/library.js`,
		filesources = [cssfile,libjsfile,jsfile];
  	return target.pipe(inject(gulp.src(filesources,{read: false}),{
			transform: transform}))

This task will inject style.min.css in your html page. and library & static.min.js file in javascript section.

You also need to specify these tags into html page to inject css and js.
Place this tag where-ever you want to inject your css (replace # with <)
#!– inject:css –>
#!– endinject –>

For js use below tag
#!– inject:js –>
#!– endinject –>

Leave a Reply

Your email address will not be published. Required fields are marked *