Last Updated: September 15, 2020
·
40.51K
· nelsonbrandao

Inject JS and CSS into HTML using Gulp

Frameworks like Ruby on Rails automatically inject all JS and CSS files into the HTML. This is also possible on a JS-based stack using Gulp and two plugins.

Wiredep for external libraries and gulp-inject for our own files.

Wiredep

Wiredep will scan our Bower config file for dependencies, determine the order to be included and insert them into the HTML file. This is possible thanks to the main field on the library bower.json that tells the primary acting files necessary to use the package.

{
    "name": "jquery",
    "version": "2.1.4",
    "main": "dist/jquery.js"
}

In your gulpfile.js we define the following task.

var gulp = require('gulp');
var wiredep = require('wiredep').stream;

var paths = {
    (...)
};

gulp.task('inject-vendor', function() {
    gulp.src(paths.index)
        .pipe(wiredep({}))
        .pipe(gulp.dest('./www'));
});

And in our index.html we add the following annotation.

<html>
    <head>
        <! -- bower:css -->
        <! -- endbower -->
    </head>
     <body>
        (...)
        <! -- bower:js -->
        <! -- endbower -->
    </body>
</html>

Now every time we run the task the libraries files will appear inside the annotation. We can even make it automatically run every time a new dependency is installed by adding the following lines to our .bowerrc file.

{
  "script": {
    "postinstall": "gulp inject-vendor"
  }
}

Gulp-Inject

Gulp-inject will read every file and inject them into placeholders just like Wiredep. This is done with another gulp task.

var inject = require('gulp-inject');

(...)

gulp.task('inject-own', function() {
    gulp.src(paths.index)
        .pipe(inject(gulp.src(paths.sources, {read: false})))
        .pipe(gulp.dest('./www'));
});

And in our index.html.

<html>
    <head>
      <!-- bower:css -->
      <!-- endbower -->

      <!-- inject:css -->
      <!-- endinject -->
    </head>
    <body>
      <!-- bower:js -->
      <!-- endbower -->

      <!-- inject:js -->
      <!-- endinject -->
    </body>
</html>

1 Response
Add your response

you can use bindep ... (npm bindep) it has many things and permits to create complex projects with submodules

over 1 year ago ·