为什么grunt-contrib-watch的livereload功能不能正常工作?

10

我很难让Grunt的“实时重新加载”功能(如grunt-contrib-watch中实现的)在我的应用程序中起作用。最终我不得不咬紧牙关,尝试做出一个最小的示例。希望有人能轻松注意到缺少了什么。

文件结构:

├── Gruntfile.js
├── package.json
├── index.html

package.json

{
  "name": "livereloadTest",
  "version": "0.1.0",
  "devDependencies": {
    "grunt": "~0.4.2",
    "grunt-contrib-watch": "~0.5.3"
  }
}

Gruntfile.js

module.exports = function(grunt) {
    grunt.initConfig({
        pkg: grunt.file.readJSON('package.json'),
        watch: {
            src: {
                files: ['*.html'],
                options: { livereload: true }
            }
        }
    });
    grunt.loadNpmTasks('grunt-contrib-watch');
};

index.html

<!doctype html>
<html>
<head><title>Test</title></head>
<body>

<p>....</p>
<script src="//localhost:35729/livereload.js"></script>

</body>
</html>

我接着运行grunt watch,并且没有出现任何问题。然而,浏览器窗口没有自动打开(应该打开吗?)。

当我在chrome中打开http://localhost:35729/时,我会收到这个json:

{"tinylr":"Welcome","version":"0.0.4"}

在该端口上尝试任何其他路径都会给我

{"error":"not_found","reason":"no such route"}
2个回答

17

http://localhost:35729/ 是实时重新加载服务器的URL,它仅用于管理实时重新加载,而不是为您的实际网站提供服务。

通常情况下,人们会使用 grunt-contrib-connect 与grunt一起来提供静态网站。然后通过访问 localhost:8000 或者您配置的其他位置来查看他们的网站。但基于您的需要,也可能是apache、nginx等提供文件。

在 grunt-contrib-connect 中还有一个 livereload 选项。 这只会将 <script src="//localhost:35729/livereload.js"></script> 标记注入到您的HTML中,而没有其他任何内容。


3
可以了!谢谢!我希望手表的文档能够更清晰地说明需要这样做... - Zach Lysobey

7
这里有一个非常简单的方法可以设置这个。只需确保你已经安装了 grunt-contrib-watchgrunt-contrib-connect 插件。这是假设你的 Gruntfile.js 在项目根目录下。还要确保在你的结束 body 标记 </body> 之前添加 <script src="//localhost:35729/livereload.js"></script>,并且你有一个 index 文件。 当你在终端中输入 grunt server 后,转到 http://localhost:9000 就可以完成设置了。
module.exports = function(grunt) {

  grunt.initConfig({
  pkg: grunt.file.readJSON('package.json'),

  watch: {
    options: {
      livereload: true,
    },
    css: {
      files: ['css/**/*.css'],
    },
    js: {
      files: ['js/**/*.js'],
    },
    html: {
      files: ['*.html'],
    }
  },
  connect: {
    server: {
      options: {
        port: 9000,
        base: '.',
        hostname: '0.0.0.0',
        protocol: 'http',
        livereload: true,
        open: true,
      }
    }
  },
});


grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-contrib-connect');

grunt.registerTask('server', ['connect','watch']);

};

我一开始无法让livereload正常工作,但是查看了您的配置并将主机名和livereload添加到connect/server/options中后问题得以解决。 - Juan Stoppa
4
不不不,不应该手动添加<script src="//localhost:35729/livereload.js"></script>。如果使用正确,grunt-contrib-connect插件会自动注入它。你不希望它对已部署的版本造成干扰。 - Augie Gardner

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