问题描述
当浏览到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>