在使用gulp-concat
的情况下,是否可以将所有添加的js
包装在$(document).ready(function(){
中作为第一行,将});
包装在最后一行?
您可以使用gulp-concat-util进行
它确实连接了所有文件,并可以选择添加头行&页脚行到连接文本
var concat = require('gulp-concat-util');
gulp.task('concat:dist', function() {
gulp.src('scripts/{,*/}*.js')
.pipe(concat(pkg.name + '.js', {process: function(src) { return (src.trim() + 'n').replace(/(^|n)[ t]*('use strict'|"use strict");?s*/g, '$1'); }}))
.pipe(concat.header('(function(window, document, undefined) {n'use strict';n'))
.pipe(concat.footer('n})(window, document);n'))
.pipe(gulp.dest('dist'));
});
我也有同样的问题,决定一起破解一些东西。也许它会对你有所帮助:
// remove jquery/use strict from independent files
// prior to concatenation, so all files are in the same context
function removeWrap( ) {
const readFileAsync = (filename) => {
return new Promise( (resolve) => {
fs.readFile('./src/js/' + filename, 'utf-8', function(err, content) {
let lines = content.split('n')
lines.splice(0,2)
lines.splice(lines.length -2)
let newContent = lines.join('n')
resolve( newContent)
})
})
}
fs.readdir('./src/js', function(err, filenames) {
filenames.forEach(function(filename) {
readFileAsync(filename).then( content => {
console.log( content[1] )
fs.writeFile('./src/js-temp/' + filename, content, ()=>{})
})
})
})
return Promise.resolve('the value is ignored');
}
// concat JS files
function concatFiles() {
return src('./src/js-temp/*.js')
.pipe(concat('main.js'))
.pipe(dest('./dist/js'));
}
function wrapMain() {
let header = `$(function() {
"use strict";n`
let footer = `
});`
fs.readFile('./dist/js/main.js', 'utf-8', function(err, content) {
let newContent = header + content + footer
fs.writeFile('./dist/js/main.js', newContent, ()=>{})
})
return Promise.resolve('the value is ignored');
}
module.exports.devJs = series(removeWrap, concatFiles, wrapMain);