[英]Angular: How to set baseHref for assets in development when using SSR
In production we are setting the base href with:在生产环境中,我们设置 base href 为:
ng build --base-href /app/
This works well.这很好用。 Especially our assets are also served at /app/assets/
as expected.特别是我们的资产也按预期在/app/assets/
提供服务。
I cannot achieve the same effect in development however, where we run:但是,在我们运行的地方,我无法在开发中达到相同的效果:
ng run project:serve-ssr
Assets remain at /assets
and are not accessible at /app/assets
.资产保留在/assets
中,无法在/app/assets
中访问。
Things I have tried in angular.json
我在angular.json
中尝试过的事情
architect.build.options.baseHref
设置architect.build.options.baseHref
architect.serve.options.servePath
设置architect.serve.options.servePath
architect.server.options.servePath
(not allowed)设置architect.server.options.servePath
(不允许)architect.serve-ssr.options.servePath
(not allowed)设置architect.serve-ssr.options.servePath
(不允许) I have also tried to set the DI token APP_BASE_HREF
and provide it in the AppModue, but to no effect.我还尝试设置 DI 令牌APP_BASE_HREF
并在 AppModue 中提供它,但没有效果。
Assuming you are using @nguniversal we solved this by creating a virtual path prefix in server.ts
:假设您使用的是@nguniversal ,我们通过在server.ts
中创建一个虚拟路径前缀来解决这个问题:
server.use(process.emv.BASE_HREF, express.static(distFolder));
The BASE_HREF
is set as an environment variable during app start: BASE_HREF
在应用程序启动期间设置为环境变量:
BASE_HREF=/app ng run project:serve-ssr
I ended up, rewriting the url in the express server in development.最后,我在开发中的 express 服务器中重写了 url。 Not super happy with that though, so if anybody has a better answer, I will happily accept that.不过对此并不满意,所以如果有人有更好的答案,我会很乐意接受。
In server.ts
:在server.ts
中:
if (environment.removeAssetsPrefix.length) {
server.use((req, _, next) => {
if (req.url.startsWith(environment.removeAssetsPrefix + '/assets/')) {
req.url = req.url.substring(environment.removeAssetsPrefix.length);
}
next();
});
}
In environment.ts
:在environment.ts
:
export const environment = {
...
removeAssetsPrefix: '/app'
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.