如何在gulp构建期间将内容插入到文件中?

Che*_*hev 10 javascript stream node.js angularjs gulp

我设法使用一个名为gulp-insert的gulp插件完成我的任务,如下所示:

gulp.task('compile-js', function () {
  // Minify and bundle client scripts.
  var scripts = gulp.src([
    srcDir + '/routes/**/*.js',
    srcDir + '/shared/js/**/*.js'
  ])
    // Sort angular files so the module definition appears
    // first in the bundle.
    .pipe(gulpAngularFilesort())
    // Add angular dependency injection annotations before
    // minifying the bundle.
    .pipe(gulpNgAnnotate())
    // Begin building source maps for easy debugging of the
    // bundled code.
    .pipe(gulpSourcemaps.init())
    .pipe(gulpConcat('bundle.js'))
    // Buffer the bundle.js file and replace the appConfig
    // placeholder string with a stringified config object.
    .pipe(gulpInsert.transform(function (contents) {
      return contents.replace("'{{{appConfigObj}}}'", JSON.stringify(config));
    }))
    .pipe(gulpUglify())
    // Finish off sourcemap tracking and write the map to the
    // bottom of the bundle file.
    .pipe(gulpSourcemaps.write())
    .pipe(gulp.dest(buildDir + '/shared/js'));

  return scripts.pipe(gulpLivereload());
});
Run Code Online (Sandbox Code Playgroud)

我正在做的是阅读我们的应用程序的配置文件,该文件由npm上的配置模块管理.从服务器端代码获取配置文件非常简单var config = require('config');,但我们是一个单页面应用程序,经常需要访问客户端的配置设置.为此,我将配置对象填充到Angular服务中.

这是Gulp构建之前的Angular服务.

angular.module('app')
  .factory('appConfig', function () {
    return '{{{appConfigObj}}}';
  });
Run Code Online (Sandbox Code Playgroud)

占位符是一个字符串,因此它是一些有效的JavaScript,用于处理文件的其他一些gulp插件.该gulpInsert实用程序允许我像这样插入配置.

.pipe(gulpInsert.transform(function (contents) {
  return contents.replace("'{{{appConfigObj}}}'", JSON.stringify(config));
}))
Run Code Online (Sandbox Code Playgroud)

这有效,但感觉有点hacky.更不用说它必须缓冲整个捆绑文件,以便我可以执行操作.是否有更优雅的方式来完成同样的事情?优选地,允许流保持平稳流动而不在末端缓冲整个束?谢谢!

tom*_*ico 5

你检查过gulp-replace-task吗?

就像是

[...]
.pipe(gulpSourcemaps.init())
.pipe(replace({
  patterns: [{
    match: '{{{appConfigObj}}}',
    replacement: config
  }],
  usePrefix: false
})
.pipe(gulpUglify())
[...]
Run Code Online (Sandbox Code Playgroud)