gulp-livereload 如何使用 https?

12

我一直在使用livereload Chrome扩展程序,它会在文档中插入一个http://[...]/livereload.js的脚本。不幸的是,我正在处理需要https的项目,我希望在本地复制这个项目,但我并不一定需要这样做,因为我可以更改不同环境下的协议。我想知道是否可能将gulp-livereload设置为通过https加载?

我尝试了一些方法,例如手动添加脚本,但没有成功,因为我遇到了连接错误(GET https://127.0.0.1:35729/livereload.js?snipver=1 net::ERR_CONNECTION_CLOSED):

var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'https://127.0.0.1:35729/livereload.js?snipver=1';
document.getElementsByTagName('body')[0].appendChild(script)
2个回答

5

我能想到的两个解决方案:

1. 自己托管客户端

https://github.com/livereload/livereload-js

将其安装为依赖项:

bower install livereload-js --save-dev

或者

npm install livereload-js --save

然后像包含常规脚本一样包含它即可。不过,请注意下列注意事项和限制

/path/to/dist/livereload.js?host=localhost

2. 代理客户端脚本

这个过程比较复杂,但能确保有效。在你的gulpfile中创建一个HTTPS服务器(可以放在watch任务里)。

https://github.com/nodejitsu/node-http-proxy

https://github.com/nodejitsu/node-http-proxy#using-https

httpProxy.createServer({
  ssl: {
    key: fs.readFileSync('valid-ssl-key.pem', 'utf8'),
    cert: fs.readFileSync('valid-ssl-cert.pem', 'utf8')
  },
  target: 'https://localhost:35729',
  secure: true // Depends on your needs, could be false.
}).listen(443);

然后,您可以引用代理脚本。
https://127.0.0.1:443/livereload.js?snipver=1

3
虽然API文档中没有提到添加密钥/证书参数,但实际上是可行的。
gulp.task('run-reload-server', function() {
  livereload.listen({
    host: "my.domain.com",
    port: 35729,
    key: fs.readFileSync(path.join(__dirname, 'livereload.key'), 'utf-8'),
    cert: fs.readFileSync(path.join(__dirname, 'livereload.crt'), 'utf-8'),
  });
});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接