Inject CSS with gulp-inject

inject css with gulp

Overview

In latest posts I have started to build front-end build pipeline with Gulp for my ASP.NET Core Web App. All of this on Ubuntu. I have been able to produce packages to output folder, however I still have hard-coded references to css and js files in my html page. Luckily it’s possible to inject CSS with Gulp.

All code can be found on frontendpipeline branch, but please keep in mind that this can be changed. Please take a look on master if you have any issues.

gulp-inject

You can inject CSS and JS with Gulp by using gulp-inject.

$ npm install --save-dev gulp-inject

Gulp

var gulp = require('gulp');
var gutil = require('gulp-util');
var mainBowerFiles = require('gulp-main-bower-files');
var gulpDebug = require('gulp-debug');
var inject = require('gulp-inject');

var publishFolder = 'public';

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

});


gulp.task('default', function() {
 // place code for your default task here
 gutil.log('gulp started') 
});

gulp.task('publish', ['default'], function() {
 
 
 gulp.src('./bower.json')
 .pipe(mainBowerFiles())
 .pipe(gulpDebug())
 .pipe(gulp.dest(publishFolder)); 

 var sources = gulp.src('**/*.css', { read: false, cwd: __dirname + '/public'} )
 .pipe(gulpDebug({title:'d'}));
 
 // copy any html files in source/ to public/
 gutil.log('moving index.html file and auto-include');
 gulp.src('index.html')
 .pipe(inject(sources))
 .pipe(gulp.dest(publishFolder));
});

HTML

Using following clause will allow me to auto-include all css files:
<!– inject:css –>
<!– endinject –>

 

Bower.JSON

One slight change to bower.json and we are done:

  "overrides": {
  "bootstrap": {
    "main": [
      "dist/css/bootstrap.css"
    ]
  }

This will force inject to load only this one file.

Inject css with gulp

Final HTML file ok, we have this specific bootstrap.css file included there.

<html>

<head>
 <title>Shout</title>
 
 <!-- inject:css -->
 <link rel="stylesheet" href="/bootstrap/dist/css/bootstrap.css">
 <!-- endinject -->
 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>

 
 <script>
 $(document).ready(function() {
 $.ajax({
 url: "http://localhost:5000/api/user"
 }).then(function(data) {
 $('.userName').append(data.UserName);
 });
});
 </script>
</head>

<body>
 <div class="container">
 <h1>Hello from Bootstrap</h1>
 <div>
 <p class="userName">The UserName is </p>
 </div>
 </div>
 

</body>

Leave a Reply

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