javascriptgulpgulp-inject

Include CDN sources in gulp-inject


I am trying to get CDN and other HTTP resources into a script that is modified by gulp-inject.

I created a corresponding issue at the repository.

The gist is that I would like something along these lines to work:

var sources = [
  "http://cdnjs.cloudflare.com/ajax/libs/jasmine/1.3.1/jasmine.js",
  "./spec/test.js"
]

gulp.task('source', function () {
   gulp.src("src/my.html")
       .pipe(inject(sources))
       .dest("dest/")
})

With that result being the following included in dest/my.html:

<script src='http://cdnjs.cloudflare.com/ajax/libs/jasmine/1.3.1/jasmine.js'>
</script>
<script src='/spec/test.js'></script>

Anyone have any thoughts?


Solution

  • I wrote a plugin, gulp-cdnizer, specifically to help with this situation.

    It's designed to allow you to keep all your CDN sources local during development, then replace the local path with a CDN path when you build your distribution.

    Basically, you install your vendor scripts using bower or just copy-and-paste, and inject them into your HTML using the local path. Then, pipe the results of gulp-inject into gulp-cdnizer, and it will replace the local paths with the CDN path.

    gulp.task('source', function () {
       return gulp.src("src/my.html")
           .pipe(inject(sources)) // only local sources
           .pipe(cdnizer([
               {
                   package: 'jasmine',
                   file: 'bower_components/jasmine/jasmine.js',
                   cdn: 'http://cdnjs.cloudflare.com/ajax/libs/jasmine/${version}/jasmine.js'
               }
           ])
           .dest("dest/")
    });
    

    I like doing it this way a lot better, because you can still develop offline. The cdnizer library can also handle local fallbacks, which makes sure your page still works if the CDN fails (for whatever reason).