2015-04-06 61 views
0

我只想加載一個使用jQuery代碼的JS文件,但我很困惑如何做到最好。我擔心的事情是做一些草率像下面來解決下$(document).ready(function(){});如何將多個jQuery文件連接成一個使用Gulp?

gulp.task('compile-js', function() { 
    gulp.src(['./js/initialization.js', './stuff.js'./js/end.js']) 
     .pipe(concat('script.js')) 
     .pipe(gulp.dest('./public/javascripts/')); 
}); 

其中initialization.jsend.js都爲document.ready功能的包裝加載所有腳本的問題(我知道笑,因此詢問)

有沒有更好的方法呢?

回答

0

寫一飲而盡文件,讓我們把它叫做 'jQuery的noconflict.js'

var through = require('through2'); 
var gutil = require('gulp-util'); 
var fs = require('fs'); 

module.exports = function(){ 
    var stream = through.obj(function(file, enc, cb) { 
    if (file.isStream()) { 
     this.emit('error', new PluginError(PLUGIN_NAME, 'Streams are not supported!')); 
     return cb(); 
    } 

    if (file.isBuffer()) { 
     var contents = file.contents.toString(); 
     file.contents = Buffer.concat([new Buffer('jQuery(document).ready(function(){'), file.contents, new Buffer('})')]); 
    } 

    cb(null, file); 
    }, function(){ 

    }) 

    return stream; 
}; 

您可能需要 '故宮安裝through2'

現在在你的gulpfile.js

var gulp = require('gulp'); 
var concat = require('gulp-concat'); 
var jquery = require('./jquery-noconflict'); 

gulp.task('compile-js', function(){ 
    gulp.src('./stuff.js') 
     .pipe(concat('script.js')) 
     .pipe(jquery()) 
     .pipe(gulp.dest('./public/javascripts/')) 
}) 
相關問題