【问题标题】:How to wrap gulp scripts with jQuery document ready如何用准备好的 jQuery 文档包装 gulp 脚本
【发布时间】:2021-02-22 08:42:50
【问题描述】:

我想用jQuery(document).ready(function($){...}); 包装gulp 处理过的咖啡脚本。这是因为 jQuery 的项目实现使用了jQuery,而咖啡脚本文件使用了$

由于这是一个有着悠久历史的老项目,我无法更改 jQuery 的实现方式。此外,编辑所有 JS 文件以使用 jQuery 而不是 $ 可能会在代码库的其他区域产生问题。

gulpfile.js中的相关代码

gulp.task('components-scripts', function () {
    var components = getComponentGlobs('coffee');
    gulp.src(components)
        .pipe(sourcemaps.init())
        .pipe(concat('main.js'))
        .pipe(coffee().on('error', util.log))
        .pipe(sourcemaps.write())
        .pipe(gulp.dest(path.source + 'scripts'));
});

将在script.js 中产生类似的内容:

(function() {
  // All processed coffee script code are here
}).call(this);

我希望它看起来像这样:

(function() {
  jQuery(document).ready(function($) {
    // All processed coffee script code are here
  });
}).call(this);

我在gulpfile.js中使用gulp-coffee

【问题讨论】:

    标签: gulp coffeescript


    【解决方案1】:

    我最终使用了gulp-inject-string

    gulp.task('components-scripts', function () {
        var components = getComponentGlobs('coffee');
        gulp.src(components)
            .pipe(sourcemaps.init())
            .pipe(concat('main.js'))
            .pipe(coffee().on('error', util.log))
            .pipe(inject.after('(function() {', '\njQuery(document).ready(function ($) {\n'))
            .pipe(inject.before('}).call(this);', '});\n'))
            .pipe(sourcemaps.write())
            .pipe(gulp.dest(path.source + 'scripts'));
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多