【问题标题】:Gulp-concat: wrap all js in a unique $(document)Gulp-concat:将所有 js 包装在一个唯一的 $(document) 中
【发布时间】:2015-12-31 19:59:22
【问题描述】:

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

【问题讨论】:

    标签: laravel gulp gulp-concat


    【解决方案1】:

    您可以为此使用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'));
    });
    

    【讨论】:

    • 谢谢,{,*/}*gulp.src 中有什么作用?我经常使用/**/*.js'concat:dist' 只是一个名字还是什么?
    • concat:dist 只是一个任务的名称.. 你可以给任何你喜欢的名字。它也是一个正则表达式,只需 google gulp src 正则表达式即可了解更多
    • 感谢您帮助我发现这一点。我一直在使用 gulp-concat 但想将所有内容都包装在 SEAF 中 - (function() {...})(); - 这就是门票。从现在开始我将使用gulp-concat-util
    【解决方案2】:

    我有同样的问题,并决定一起破解一些东西。或许对你有帮助:

    // 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);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-07
      • 1970-01-01
      • 2023-02-26
      • 2014-04-23
      • 1970-01-01
      相关资源
      最近更新 更多