如何解决在 webjar 中发布的 Angular 应用程序:baseHref 问题
我需要将我的 Angular 前端打包到 webjar 中,以便通过 Maven 导入到任何 Java 后端。
我做到了,所以现在我有一个带有以下 application.properties
server.servlet.context-path=/demo
以及以下 pom.xml
<dependencies>
<dependency>
<groupId>com.foo.bar</groupId>
<artifactId>angular-frontend-webjar</artifactId>
<version>1.0.0</version>
</dependency>
...
还有这个配置
@Configuration
public class WebjarConfig extends WebMvcConfigurationSupport {
@Override
protected void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/meta-inf/resources/webjars/");
}
到目前为止一切顺利,我可以通过以下网址访问前端:http://localhost:8080/demo/index.html
但是 Angular 前端引导程序失败,因为 JS/CSS 文件未正确加载。
原因是:后端的contextpath是/demo
,而前端的<base href="/">
中指定的标签index.html
是"/"
(根)。
所以浏览器尝试从 http://localhost:8080/main-es2015.js 而不是 http://localhost:8080/demo/main-es2015.js 下载 JS
我从 angular doc 中读到可以在前端构建时使用命令 ng build --base-href /actualcontextpath/
覆盖 base href,
但在构建时,我不知道将使用前端导入 webjar 的 Spring Boot 应用程序的 contextpath。
有什么帮助吗?
解决方法
你试过了吗?
在你的 pom.xml 上:
<build>
<finalName>${project.parent.name}</finalName>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>${version.spring-boot}</version>
<!-- Habilitamos la generacion de un properties con la info de maven
accesible desde spring-boot,como el nombre que le queramos dar a la apliacion,para facilitar el desarrollo -->
<executions>
<execution>
<goals>
<goal>build-info</goal>
</goals>
<configuration>
<additionalProperties>
<applicationName>${project.parent.name}</applicationName>
</additionalProperties>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
然后在您的配置 java 文件中您可以访问属性“applicationName”
@SpringBootApplication
public class DemoApplication extends SpringBootServletInitializer {
@Autowired
BuildProperties buildProperties;
...
你可以这样设置应用上下文:
@Bean
public WebServerFactoryCustomizer<ConfigurableServletWebServerFactory>
webServerFactoryCustomizer() {
return factory -> factory.setContextPath("/"+buildProperties.get("applicationName"));
}
因此,在 pom.xml applicationName --> "demo" 和您的 java spring boot 配置中,您将上下文路径设置为 "demo"。
通过这种方式,您可以使用更动态的路由来设置上下文路径。如果你不想玩 pom.xml 你只需要使用这个:
@Bean
public WebServerFactoryCustomizer<ConfigurableServletWebServerFactory>
webServerFactoryCustomizer() {
return factory -> factory.setContextPath("/demo");
}
祝你好运,对不起我的英语。
,好的好的,我现在知道了。
将您的基本 href 设置为“./”
像这样加载你的 webjar 脚本 src="webjars/..." 在 webjars 之前没有“/”。
最后一点是让 Angular 管理 Spring 之外的路由。你可以查看这个 repo 以获得一个想法,阅读自述文件中的 las 部分:
https://github.com/FraktonDevelopers/spring-boot-angular-maven-build
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。