如何在吞噬生成过程中将内容插入到文件中?

我设法完成我的任务使用一个叫做gulp插入的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()); }); 

我正在做的是读取我们的应用程序的configuration文件,由npm上的configuration模块pipe理。 从服务器端代码获取我们的configuration文件是使用var config = require('config'); ,但我们是一个单页面的应用程序,经常需要访问客户端的configuration设置。 要做到这一点,我把configuration对象填入一个Angular服务。

gulp build之前的Angular服务。

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

占位符是一个string,因此它是其他一些首先处理文件的gulp插件的有效JavaScript。 gulpInsert实用工具让我像这样插入configuration。

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

这工作,但感觉有点哈克。 更何况,它必须缓冲整个捆绑文件,所以我可以执行操作。 有没有更好的方法来完成同样的事情? 最好是一个让stream保持平稳stream动而不会缓冲整个束的结果? 谢谢!

你检查了gulp-replace-task吗?

就像是

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

无可否认,这也感觉有点envify ,但也许稍微好一点…我在一个React项目中使用了envifyenvify gulp-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; });