GulpJS: Add Javascript and CSS dynamically in main file

Standard

Add Javascript and CSS dynamically in main file

  • Use wiredep to inject bower js and css dependencies into index.html
  • Use gulp-inject to inject custom js and css dependencies into index.html

Pre Install:

    npm install --save-dev gulp gulp-load-plugins

Install:

    npm install --save-dev wiredep gulp-inject

Syntax in HTML File for wiredep:

    <!-- bower:css -->

    <!-- endbower -->

    <!-- bower:js -->

    <!-- endbower -->

Code:

    var gulp = require('gulp');
    var $ = require('gulp-load-plugins')({ lazy: true });

    var options = {
        bowerJson: require('./bower.json'),
        directory: './bower_components/',
        ignorePath:  '../..'
    }

    gulp.task('injectJS', function () {
        var wiredep = require('wiredep').stream;

        return gulp
            .src('./src/index.html')
            .pipe(wiredep(options))
            .pipe($.inject(gulp.src('modules/home/**/*.js')))
            .pipe(gulp.dest('./build/'));
    });

Execute:

    gulp injectJS

Syntax in HTML File for gulp-inject:

    <!-- inject:css -->

    <!-- endinject -->

    <!-- inject:js -->

    <!-- endinject -->  

Code:

    var gulp = require('gulp');
    var $ = require('gulp-load-plugins')({ lazy: true });

    gulp.task('injectCSS', function () {

        return gulp
            .src('./src/index.html')
            .pipe($.inject(gulp.src('content/**/*.css')))
            .pipe(gulp.dest('./build/content/'));
    });

Execute:

    gulp injectCSS
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s