gpt4 book ai didi

javascript - 使用 gulp 在页面上临时添加脚本

转载 作者:太空宇宙 更新时间:2023-11-04 02:09:50 28 4
gpt4 key购买 nike

我目前正在开发一个 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 并且我也想这样做。提前致谢。

--- 更新--- 2017 年 3 月 14 日 ---

我使用下面的代码更新了 gulpfile.js 服务器,但是 test.js 被永久注入(inject)到该文件中。

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 并在服务器结束时删除 if 。

最佳答案

我通过使用 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 相同的位置。

关于javascript - 使用 gulp 在页面上临时添加脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42763179/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com