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

时间:2015-06-18 21:59:01

标签: javascript angularjs node.js stream 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());
});

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

这是gulp build之前的Angular服务。

angular.module('app')
  .factory('appConfig', function () {
    return '{{{appConfigObj}}}';
  });

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

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

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

2 个答案:

答案 0 :(得分:5)

您检查过gulp-replace-task吗?

这样的东西
[...]
.pipe(gulpSourcemaps.init())
.pipe(replace({
  patterns: [{
    match: '{{{appConfigObj}}}',
    replacement: config
  }],
  usePrefix: false
})
.pipe(gulpUglify())
[...]

答案 1 :(得分:2)

不可否认,这也感觉有点hacky,但也许稍微好一些......我在React项目中使用envifygulp-env。你可以这样做。

gulpfile.js:

var config = require('config');
var envify = require('envify');

gulp.task('env', function () {
    env({
        vars: {
            APP_CONFIG: JSON.stringify(config)
        }
    });
});

gulp.task('compile-js', ['env'], function () {
  // ... replace `gulp-insert` with `envify`
});

工厂:

angular.module('app')
  .factory('appConfig', function () {
    return process.env.APP_CONFIG;
  });
相关问题