如何在Spring Boot中为JavaScript配置Thymeleaf模板引擎?
在Spring Boot中用Thymeleaf预处理独立JavaScript文件
要让Thymeleaf处理单独的JS文件,核心是把JS文件纳入Thymeleaf的模板处理流程,而不是让它直接作为静态资源返回。具体操作步骤如下:
1. 移动JS文件到模板目录
把你的scripts.js从默认的静态资源目录(src/main/resources/static/js)移到Thymeleaf的模板目录下,比如新建src/main/resources/templates/js文件夹,把JS文件放进去。这样Thymeleaf才会把它当成需要预处理的模板文件。
2. 配置Thymeleaf支持JS后缀
在application.properties(或application.yml)里添加配置,让Thymeleaf能识别.js后缀的模板:
properties配置:
spring.thymeleaf.suffix=.html,.js spring.thymeleaf.content-type=text/html,application/javascript
yml配置:
spring: thymeleaf: suffix: .html,.js content-type: text/html,application/javascript
3. 配置路由转发JS请求
添加一个Spring MVC配置类,把/js/**路径的请求转发给Thymeleaf视图解析器:
import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @Configuration public class WebConfig implements WebMvcConfigurer { @Override public void addViewControllers(ViewControllerRegistry registry) { // 把/js/xxx.js的请求映射到模板目录下的js/xxx.js registry.addViewController("/js/{fileName}.js") .setViewName("js/{fileName}"); } }
4. 在JS文件中使用Thymeleaf语法
现在可以在scripts.js里直接写Thymeleaf表达式了,推荐用内联注释语法(避免静态环境报错):
// 获取应用根路径 const baseUrl = /*[[@{/}]]*/ ''; // 获取后端传递的变量 const appVersion = /*[[${appVersion}]]*/ '1.0.0';
Thymeleaf预处理时会把/*[[...]]*/里的表达式替换成实际值,后面的字符串是给静态环境用的默认值。
5. 保持HTML中的引用不变
原来的HTML引用不需要修改,请求会自动走Thymeleaf处理流程:
<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head></head> <body> <script th:src="@{/js/scripts.js}"></script> </body> </html>
如果只是少量JS代码,也可以直接把JS内联到HTML里,用<script th:inline="javascript">包裹,但独立JS文件的场景下,上面的方案更合适。
内容的提问来源于stack exchange,提问作者Slevin
相关产品推荐
相关产品推荐

