Changing Angular 5 publish url at runtime

≡放荡痞女 提交于 2019-12-03 09:42:37
ZeroKoll

Setting the deployUrl setting in .angular-cli.json, or passing in the --deploy-url to the build command does 2 things. It makes sure that the script includes in the index.html file are using that as the base, and it sets a variable that makes sure that webpack adds that as the "base path" for any lazy loaded modules. That much we agree on I guess, and figuring out where to load the scripts from in the html is pretty simple. However, setting the path that webpack should use is a bit more tricky... The value used by webpack is not named __webpack_public_path__ as mentioned in the linked suggestion and in the documentation.

You even mention the solution yourself when you say that setting the --deploy-url causes the following

__webpack_require__.p = "https://example.com/myapp1"; 

So, instead of setting the __webpack_public_path__ at runtime, as mentioned explained in the documentation, you have to set the __webpack_require__.p property.

The easiest way to do this is to just set it in the app.module.ts file. Doing something like this should work in your scenario

index.html

<script>
  window.config = { basePath: 'https://sub1.example.com/myapp1' }
</script>`

app.module.ts

// imports etc...

declare var __webpack_require__: any;
declare var config;
__webpack_require__.p = window.config.basePath;

@NgModule({})
...

This will make sure that the __webpack_require__.p property is set to the configured value on load.

In this case I just added the configured value as a config variable on the window object, but you can fetch it from wherever you want. And to keep it simple, I just assumed the value would always be there... You might want to have a fallback in case the config object isn't available, or the basePath property isn't set.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!