微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

使用Webpack开发服务器时访问Thymeleaf Spring Boot application.properties

如何解决使用Webpack开发服务器时访问Thymeleaf Spring Boot application.properties

当浏览到http:// localhost:8081上的应用程序时,我可以从application.properties访问相关的属性值,但不能通过http:// localhost:9090使用webpack devserver。

webpack.dev.js(开发服务器)

const merge = require('webpack-merge');
const common = require('./webpack.common.js');

module.exports = merge(common,{

    plugins: [
      new CleanWebpackPlugin(),new HtmlWebpackPlugin({
          template: 'src/main/resources/templates/index.html',title: 'Example Application'
      }),new webpack.HotModuleReplacementPlugin(),new webpack.ProvidePlugin({
          $: 'jquery',jQuery: 'jquery','window.jQuery': 'jquery',Popper: ['popper.js','default']
      })
    ],.
    .

    mode: 'development',devServer: {
        historyApiFallback: true,hot: true,port: 9090,proxy: {
            '/': {
                target: 'http://localhost:8081',secure: false,prependpath: false
            }
        },publicPath: 'http://localhost:9090/'
    },devtool: 'inline-source-map',});

index.html

 <html>
    <head>
       .
       .
      <script th:inline="javascript">
        var SERVICES_URL = [[${servicesUrl}]];
        var MAPS_URL = [[${mapsUrl}]];
      </script>     
   </head>
   <body>
      <div id="react"></div>
      <script src="/bundle.js"></script> 
   </body>
</html>

application.properties

services.url=https://example1.com
maps.url=https://example2.com

在使用webpack开发服务器时,在任何javascript文件中访问变量SERVICES_URL时,都会出现以下错误,因为Thymeleaf没有为变量分配值。

SyntaxError: missing ] after element list

我认为它在webpack devserver上不起作用,因为它只提供前端代码,而不是嵌入式Tomcat服务器,后者也提供服务器端代码

解决方法

此问题的解决方案是从Webpack配置文件中删除HtmlWebpackPlugin,以便不是从资源文件中加载索引,而是从Thymeleaf完成任务后的响应中加载索引。

<audio id="myaudio" controls loop>
  <source src="https://www.w3schools.com/jsref/horse.mp3" type="audio/mpeg">
  Your browser does not support the audio element.
</audio>

<img src="https://upload.wikimedia.org/wikipedia/commons/thumb/3/3f/Mute_Icon.svg/1200px-Mute_Icon.svg.png" 
            style="height: 80px; width: 80px" id="imgClickAndChange" onclick="changeImage()"  />
</p>
<script language="javascript">
    
function changeImage() {
var x = document.getElementById("myAudio");
        if (document.getElementById("imgClickAndChange").src == "https://www.iconfinder.com/data/icons/octicons/1024/unmute-512.png") 
        {
            document.getElementById("imgClickAndChange").src = "https://upload.wikimedia.org/wikipedia/commons/thumb/3/3f/Mute_Icon.svg/1200px-Mute_Icon.svg.png";
             x.play();
 }
        else 
        {
            document.getElementById("imgClickAndChange").src = "https://www.iconfinder.com/data/icons/octicons/1024/unmute-512.png";
        x.pause();
}
    }
</script>

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。