問題描述
我正在使用 gulp 對我的 javascript 文件進行 uglify 并準備好用于生產.我所擁有的是這段代碼:
I am using gulp to uglify and make ready my javascript files for production. What I have is this code:
var concat = require('gulp-concat');
var del = require('del');
var gulp = require('gulp');
var gzip = require('gulp-gzip');
var less = require('gulp-less');
var minifyCSS = require('gulp-minify-css');
var uglify = require('gulp-uglify');
var js = {
src: [
// more files here
'temp/js/app/appConfig.js',
'temp/js/app/appConstant.js',
// more files here
],
gulp.task('scripts', ['clean-js'], function () {
return gulp.src(js.src).pipe(uglify())
.pipe(concat('js.min.js'))
.pipe(gulp.dest('content/bundles/'))
.pipe(gzip(gzip_options))
.pipe(gulp.dest('content/bundles/'));
});
我需要做的是替換字符串:
What I need to do is to replace the string:
dataServer: "http://localhost:3048",
與
dataServer: "http://example.com",
在文件'temp/js/app/appConstant.js'中,
In the file 'temp/js/app/appConstant.js',
我正在尋找一些建議.例如,也許我應該復制 appConstant.js 文件,更改它(不確定如何)并將 appConstantEdited.js 包含在 js.src 中?
I'm looking for some suggestions. For example perhaps I should make a copy of the appConstant.js file, change that (not sure how) and include appConstantEdited.js in the js.src?
但我不確定 gulp 如何復制文件并替換文件中的字符串.
But I am not sure with gulp how to make a copy of a file and replace a string inside a file.
您提供的任何幫助將不勝感激.
Any help you give would be much appreciated.
推薦答案
Gulp 流式輸入,執行所有轉換,然后流式輸出.使用 Gulp 時,在兩者之間保存臨時文件是 AFAIK 非慣用的.
Gulp streams input, does all transformations, and then streams output. Saving temporary files in between is AFAIK non-idiomatic when using Gulp.
相反,您正在尋找的是一種替換內容的流式傳輸方式.自己寫東西會比較容易,或者你可以使用現有的插件.對我來說,gulp-replace
效果很好.
Instead, what you're looking for, is a streaming-way of replacing content. It would be moderately easy to write something yourself, or you could use an existing plugin. For me, gulp-replace
has worked quite well.
如果您想在所有文件中進行替換,您可以像這樣輕松更改任務:
If you want to do the replacement in all files it's easy to change your task like this:
var replace = require('gulp-replace');
gulp.task('scripts', ['clean-js'], function () {
return gulp.src(js.src)
.pipe(replace(/http://localhost:d+/g, 'http://example.com'))
.pipe(uglify())
.pipe(concat('js.min.js'))
.pipe(gulp.dest('content/bundles/'))
.pipe(gzip(gzip_options))
.pipe(gulp.dest('content/bundles/'));
});
你也可以只對你期望模式所在的文件執行 gulp.src
,并通過 gulp-replace
將它們單獨流式傳輸,將其與 gulp.src
之后所有其他文件的流.
You could also do gulp.src
just on the files you expect the pattern to be in, and stream them seperately through gulp-replace
, merging it with a gulp.src
stream of all the other files afterwards.
這篇關于如何使用 gulp 替換文件中的字符串?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!