如何获取webpack的publicPath?

5

我正在使用以下代码将图标添加到MdIconRegistry:

constructor(iconRegistry: MdIconRegistry, sanitizer: DomSanitizer) {
  iconRegistry.addSvgIconSet(
    sanitizer.bypassSecurityTrustResourceUrl('/assets/svg-sprite-action-symbol.svg'));
  iconRegistry.addSvgIconSet(
    sanitizer.bypassSecurityTrustResourceUrl('/assets/svg-sprite-content-symbol.svg'));
  iconRegistry.addSvgIconSet(
    sanitizer.bypassSecurityTrustResourceUrl('/assets/svg-sprite-navigation-symbol.svg'));
}

很不幸,在使用ng [build|serve] --deploy-url=/public/时会出现问题(在生产环境中,我希望将ng build输出部署到CDN上)。

有没有一种方法可以从我的Angular组件中访问webpack的publicPath变量,以便我可以指定相对于该变量的svg图标的URL?

我查看了ng build输出,发现该变量在inline.bundle.js中设置,但我不确定如何正确访问它。

/******/    __webpack_require__.p = "/public/";

1
我不确定它是否应该对应用程序可用。我想更好的方法是将其公开为环境变量。 - Estus Flask
1
你可以查看这篇文章 https://webpack.js.org/guides/public-path/。很可能是你想要的。 - FAISAL
Petr TIchy在Youtube上制作了一系列不错的视频。https://www.youtube.com/playlist?list=PLkEZWD8wbltnRp6nRR8kv97RbpcUdNawY 这里有他的webpack.config.js示例,包括Twitter Bootstrap。您可以从中看到他如何处理图像。https://github.com/Ihatetomatoes/webpack-101-bootstrap/blob/master/webpack.config.js 有时语法会随着这些内容的发展而变化 - 因此一定要参考https://webpack.js.org/网站。 - JGFMK
2个回答

4
你可以从全局变量__webpack_public_path__中获取它。

3
如果您可以访问webpack配置文件,那么您可以轻松获取公共路径。
假设您在项目根目录中有webpack.config.js,并且您在/src/component/mycomponent.js中有组件文件。
您的webpack.config.js应该是这样的:
module.exports = {
.
.
.
 output: {
   path: "somthing",
   filename: "somthing",
   publicPath: "something"
 }
.
.
.
}

那么/src/component/mycomponent.js将会是这样的:

import webpackConfig from "../../webpack.config"

const publickPath = webpackConfig.output.publicPath

Webpack配置文件就像另一个JavaScript文件,您可以从中导入内容。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接