我正在开展一个gulp项目,我有gulpfile.js
var config = require('./config.json'),
gulp = require('gulp'),
watch = require('gulp-watch'),
connect = require('gulp-connect'),
runSequence = require('run-sequence');
gulp.task('server', function() {
connect.server({
root: './',
port: config.port,
livereload: true
});
});
gulp.task('html', function() {
gulp.src('./' + config.creatives + '/**/*.html')
.pipe(connect.reload());
});
gulp.task('watch', function() {
gulp.watch(['./' + config.creatives + '/**/*.html'], ['html']);
gulp.watch(['./' + config.creatives + '/**/*.css'], ['html']);
});
gulp.task('default', function() {
return runSequence('server', ['html', 'watch']);
});
config.json
内容
{
"port" : "2727",
"creatives" : "creatives"
}
我的问题是如何在我正在查看的页面中添加临时脚本文件?我看到connect-livereload
正在我的页面底部添加livereload.js
&我想也这样做。提前谢谢。
---更新--- 14-03-2017 ---
我使用下面的代码更新gulpfile.js
服务器,但test.js
正在永久注入该文件。
gulp.task('server', function() {
connect.server({
...
livereload: true,
middleware: function(connect, option) {
return [
function(req, res, next) {
var file, path;
if (req.url.indexOf('preview') > -1) {
file = req.url;
path = file.replace('index.html', '')
gulp.src('./' + file)
.pipe(insertLines({
'before': /<\/body>$/,
'lineBefore': '<script type="text/javascript" src="test.js"></script>'
}))
.pipe(gulp.dest('./' + path));
}
next();
}
]
}
});
});
我只需要在服务器启动时添加test.js
&amp;如果服务器结束时删除。
答案 0 :(得分:0)
我通过使用gulp编辑模块本身来解决问题 不确定这是否正确,但对我来说,这很好(现在)。
<强>解决方案强>
我制作了一个update-module.js
文件,并有以下脚本:
var gulp = require('gulp'),
tap = require('gulp-tap'),
rename = require('gulp-rename');
gulp.task('default', function() {
return gulp.src('./node_modules/connect-livereload/index.js')
.pipe(rename('~index.js'))
.pipe(gulp.dest('./node_modules/connect-livereload/'))
.pipe(tap(function(file, callback) {
var newFile = file.contents.toString(),
oldText = 'return \'<script src="\' + src + \'" async="" defer=""></script>\'',
newtext = 'return \'<script src="\' + src + \'" async="" defer=""></script><script src="http://localhost:3000/temp.js" ></script>\'';
newContents = newFile.replace(oldText, newtext);
file.contents = new Buffer(newContents);
return file;
}))
.pipe(rename('index.js'))
.pipe(gulp.dest('./node_modules/connect-livereload/'));
});
我在终端上输入gulp --gulpfile ./update-module.js
来运行此脚本一次。
它的作用是查找connect-livereload
模块并复制index.js
,将其重命名为~index.js
(用于备份),然后修改index.js
以包含我的临时脚本( temp.js
)并将其保存在与index.js
相同的位置。