简体   繁体   English

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

[英]How can I insert content into a file during a gulp build?

I managed to accomplish my task using a gulp plugin called gulp-insert like this: 我设法使用名为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());
});

What I'm doing is reading our app's configuration file which is managed by the config module on npm. 我正在做的是读取应用程序的配置文件,该文件由npm上的config模块管理。 Getting our config file from server-side code is a snap using var config = require('config'); 使用var config = require('config');从服务器端代码获取配置文件非常简单var config = require('config'); , but we're a single-page app and frequently need access to the configuration settings on the client-side. ,但我们是单页应用程序,因此经常需要访问客户端的配置设置。 To do that I stuff the config object into an Angular service. 为此,我将配置对象填充到Angular服务中。

Here's the Angular service before gulp build. 这是在构建gulp之前的Angular服务。

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

The placeholder is in a string so that it's valid JavaScript for some of the other gulp plugins that process the file first. 占位符在字符串中,因此对于其他先处理文件的gulp插件来说,它是有效的JavaScript。 The gulpInsert utility lets me insert the config like this. gulpInsert实用程序使我可以像这样插入配置。

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

This works but feels a little hacky. 这行得通,但感觉有些不客气。 Not to mention that it has to buffer the whole bundled file just so I can perform the operation. 更不用说它必须缓冲整个捆绑的文件,以便我可以执行该操作。 Is there a more elegant way to accomplish the same thing? 有没有更优雅的方式来完成同一件事? Preferably one that allows the stream to keep flowing smoothly without buffering the whole bundle at the end? 最好是一种允许流保持平稳流动而又不会在最后缓冲整个束的方法? Thanks! 谢谢!

Have you checked gulp-replace-task ? 您检查了gulp-replace-task吗?

Something like 就像是

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

Admittedly, this feels a bit hacky, too, but maybe slightly better... I'm using envify and gulp-env in a React project. 诚然,这也感觉有些envify ,但也许稍微好点了……我在React项目中使用envifyenvify gulp-env You could do something like this. 你可以做这样的事情。

gulpfile.js: 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`
});

factory: 厂:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM