Gulp-concat: 将所有的 js 包装在一个唯一的 $(document)

Gulp-concat: wrap all js in a unique $(document)

在使用 gulp-concat 的情况下,是否可以将所有添加的 js 包装在 $(document).ready(function(){ 作为第一行和 }); 作为最后一行?

你可以使用 gulp-concat-util 这个

它会连接所有文件,并可选择将 header 行和页脚行添加到连接的文本中

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, ''); }}))
    .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);