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?
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).
I used gulp-replace
for a similar use case:
html:
<!-- replace:google-places -->
gulp:
return gulp.src(path.join(conf.paths.src, '/*.html'))
.pipe($.inject(injectStyles, injectOptions))
.pipe($.inject(injectScripts, injectOptions))
.pipe($.replace('<!-- replace:google-places -->', replacePlaces)) // <-- gulp-replace
.pipe(wiredep(_.extend({}, conf.wiredep)))
.pipe(gulp.dest(path.join(conf.paths.tmp, '/serve')));
replacePlaces:
const replacePlaces = match => {
switch (process.env.NODE_ENV){
case 'dev':
return '<script src="https://maps.googleapis.com/maps/api/js....."></script>';
case 'production':
return '<script src="https://maps.googleapis.com/maps/api/js......"></script>';
default:
return match;
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.