HTML Webpack 插件将无法编译,因为 Thymeleaf 变量未定义

HTML Webpack Plugin will not compile as Thymeleaf variables are undefined

当 Webpack 编译我的包含以下 HTML 的应用程序时,它会抱怨 theme 变量未定义。

这是我的 index.html 文件:

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8"/>
</head>
<body th:class="${theme}">
    <div id="root"></div>
</body>
</html>

这是我得到的错误:

Failed to compile.

Error in Template execution failed: ReferenceError: theme is not defined

- loader.js:4 eval
/src/main/resources/templates/index.html?./~/html-webpack-plugin/lib/loader.js:4:10

同样的错误。我找到了 this issue,你只需让 webpack 像这样使用 'html-loader':

new HtmlWebpackPlugin({
    template: '!!html-loader!index.html'
})

PS: 不要忘记在使用 npm 之前安装它;)

将其放入 :

webpack.config

new HtmlWebpackPlugin({
     template: './index.ejs',
     filename: './index.html',
     minify: { collapseWhitespace: true },
     csrf: '${_csrf.token}',
}),

在您的 index.ejs 文件中放入:

<meta name="_csrf" th:content="<%= htmlWebpackPlugin.options.csrf %>"/>

我的解决方法:将 $ 替换为 <%="$"%>