如何在Gulp构建过程中将内容插入到文件中?

k10s72fa  于 2023-04-18  发布在  Gulp
关注(0)|答案(2)|浏览(286)

我使用一个名为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');从服务器端代码获取我们的配置文件是一件轻而易举的事情,但我们是一个单页应用程序,经常需要访问客户端的配置设置。为此,我将config对象放入Angular服务中。
这是gulp构建之前的Angular服务。

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

占位符是一个字符串,因此它对于首先处理该文件的其他一些Gulp插件来说是有效的JavaScript。

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

这是可行的,但感觉有点笨拙。更不用说它必须缓冲整个捆绑文件,这样我才能执行操作。有没有更优雅的方法来完成同样的事情?最好是一个允许流保持平稳流动,而不是在最后缓冲整个bundle?

q9rjltbz

q9rjltbz1#

你看过gulp-replace-task吗?
就像

[...]
.pipe(gulpSourcemaps.init())
.pipe(replace({
  patterns: [{
    match: '{{{appConfigObj}}}',
    replacement: config
  }],
  usePrefix: false
})
.pipe(gulpUglify())
[...]
fnatzsnv

fnatzsnv2#

不可否认,这也感觉有点黑客,但也许稍微好一点......我在一个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;
  });

相关问题