2

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

4

2 回答 2

5

您可以为此使用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'));
});
于 2016-01-02T08:01:09.790 回答
0

我有同样的问题,并决定一起破解一些东西。也许它会对您有所帮助:

// 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);
于 2019-07-02T04:14:19.880 回答