thymeleaf 模板的实时重新加载

Rpa*_*ant 5 spring thymeleaf livereload spring-boot-devtools spring-boot-2

当我更改 /templates 中的 thymeleaf .html 文件时,我希望浏览器自动重新加载页面。我安装了实时重新加载插件,它能够与 Spring Boot 服务器握手。但是,在更改 thymeleaf 模板文件时,我必须手动重新加载浏览器。任何我可能缺少的建议。显然我已经spring-boot-devtools启用并手动更新了属性devtools.livereload.enabled = true。并且 spring devtools 正确地反映了对构建目标中任何模板或控制器的更改,并且通过手动重新加载浏览器,我看到了更改。

根据 spring 文档。

某些资源在更改时不一定需要触发重新启动。例如,可以就地编辑 Thymeleaf 模板。默认情况下,更改 /META-INF/maven、/META-INF/resources、/resources、/static、/public 或 /templates 中的资源不会触发重新启动,但会触发实时重新加载

我让我的本地运行在损坏的 https 上。(某些证书问题,这会导致not securechrome 地址栏中出现一条消息。这可能是实时重新加载不起作用的原因。

dow*_*eit 35

经过 3 年的挫折,这里是一个可行的热交换解决方案:

https://attacomsian.com/blog/spring-boot-auto-reload-thymeleaf-templates

以下是我测试过的设置(这是我为其工作所做的唯一更改)。

application.yaml:

spring:
  thymeleaf: # Thymeleaf
    cache: false
    mode: HTML
    encoding: UTF-8
    prefix: file:src/main/resources/templates/
  resources: # Static resources
    static-locations: file:src/main/resources/static/
    cache:
      period: 0
Run Code Online (Sandbox Code Playgroud)

它能做什么:

  • static/如果您更改了或中的任何内容,则将更改应用于您的视图(和/或静态内容)templates/
  • 无需手动编译或重新启动整个 Web 服务器即可完成此操作

它不做什么:

  • 在浏览器中重新加载页面(您仍然需要在浏览器中刷新页面;顺便说一句,LiveReload Chrome 扩展也不起作用,也许使用一些 webpack 魔法可以让它工作)

这一切都假设您没有覆盖默认路径(/resources/templates, /resources/static)。

PS 我尝试过使用自签名 TLS 证书,它仍然有效。是的,它不会像 Angular 一样,立即重新加载浏览器页面。

  • 对我来说,设置 spring.thymeleaf.cache=false 就足够了。另外,您可能希望将其放入“application-development.yml”中,以避免在生产环境中出现此情况(请参阅:/sf/ask/2794482211/ -特性) (5认同)

小智 13

在 Spring Thymeleaf 中自动重新加载 HTML / CSS / JS 非常简单且无错误,仅在 IntelliJ 中进行了测试。

将其添加到 maven,使用 ${spring.version} var 或替换为您的版本:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-devtools</artifactId>
    <version>${spring.version}</version>
    <optional>true</optional>
    <scope>runtime</scope>
</dependency>
Run Code Online (Sandbox Code Playgroud)

添加到html的标题中:

<script src="http://localhost:35729/livereload.js"></script>
Run Code Online (Sandbox Code Playgroud)

使用 IntelliJ 时:

使用 Ctrl+Shift+A 写入注册表

在 IntelliJ 设置中

  • 这是这个问题的正确答案。 (2认同)

mrk*_*nic -1

编辑:

您可以使用实时重新加载插件等来启用浏览器的自动重新刷新。您可以使用http://livereload.com/extensions/

官方 Spring Boot 文档的提示如下:https ://docs.spring.io/spring-boot/docs/current/reference/html/using-boot-devtools.html#using-boot-devtools-livereload

解释为什么它不能开箱即用

我认为你在这里混合了东西。Spring Boot 应用程序中的“实时重新加载”意味着编辑 html 后无需重新启动应用程序服务器。这并不意味着您可以像angularfrom那样进行热重载webpack dev server

因此,您仍然需要触发浏览器页面的刷新。

有关 WDS 中如何工作的更多详细信息,请参阅此处:https ://webpack.js.org/concepts/hot-module-replacement/

从 spring 的角度来看https://docs.spring.io/spring-boot/docs/current/reference/html/howto-hotswapping.html