Angular 6 使用资产从 node_modules 导入 SCSS

Angular 6 import SCSS from node_modules with assets

我目前有一个库可以导出一些 SCSS,其中包含位于子文件夹中的字体路径。

我的 font.scss 文件夹 node_modules 中的 SCSS 如下所示

@font-face {
   font-family: "Daimler";
   font-weight: "normal";
   font-style: "italic";
   src: url($font-path + '.eot') format("embedded-opentype"),
   url($font-path + '.ttf') format("ttf");
}

该文件将导入到 src 文件夹中的 main.scss 文件中的 angular 项目中。该文件夹将从 angular 构建复制到具有以下设置的资产

{
   "glob": "**/*",
   "input": "nodemodules/library/fonts/",
   "output": "/assets/fonts"
}

我的问题是 $font-path 应该是什么样子,或者我需要什么来解决这个问题。我已经尝试过但没有用的东西(总是无法解析路径):

./assets/fonts/bold/xyz.eot (can't resolve because relativ path is wrong from main.scss, but should be correct since that will be the destination the files will be copied to from the angular build)

/src/assets/fonts/bold/xyz.eot (building the project works, but path is wrong on runtime)

问题是 CSS-Loader 将始终检查 url,在构建应用程序时它总是尝试解析 src/assets 的路径,其中显然没有文件,因为它们会只被复制到目标文件夹(从 cli-config)。

有什么解决办法吗?

/src/assets/fonts/bold/xyz.eot (building the project works, but path is wrong on runtime)

当您的应用构建默认时,所有文件都将位于您的 dist 文件夹中。 它看起来像这样

  • 资产
  • index.html
  • 一堆js文件和其他

你不会在根目录下有 src 文件夹。

绝对路径为 /assets/fonts/bold/xyz.eot

我认为相对路径是 ./nodemodules/library/fonts/bold/xyz.eot

很难给你一个明确的答案,因为文件夹结构因项目而异,但看起来你需要使用 Angular CLI 中的 --deploy-url 标志。

这是我的项目 package.json 的摘录:

"scripts": {
  "ng": "ng",
  "prod": "ng build --deploy-url /assets/analytics/dist/",
  "dev": "ng build --deploy-url /assets/analytics/dist/ --watch",
  "test": "ng test"
}

在我的例子中,所有字体都与主 Angular CLI 生成的包混合在 dist 文件夹中。 styles.css 文件也在那里,我对损坏的路径没有任何问题。

同样,就像我说的,您的文件夹结构可能不同,但 deploy-url 标记是一种可行的方法。