【问题标题】:Angular 6 import SCSS from node_modules with assetsAngular 6 从带有资产的 node_modules 导入 SCSS
【发布时间】:2019-01-14 07:10:21
【问题描述】:

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

  • nodemodules/library/fonts/font.scss
  • 字体文件,例如在 nodemodules/library/fonts/bold/xyz.eot

SCSS 在我的 node_modules 文件夹中的 font.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)。

有什么解决办法吗?

【问题讨论】:

    标签: angular webpack sass angular-cli css-loader


    【解决方案1】:

    /src/assets/fonts/bold/xyz.eot(构建项目有效,但路径 运行时错误)

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

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

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

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

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

    【讨论】:

    • 是的,这将是开发时的正确路径,但在运行时没有更多的 node_modules 文件夹,因此无法找到文件。
    • 如果我没记错的话,Angular cli 会在您构建生产应用程序时转换路径。
    • 应该尝试/assets/fonts/bold/xyz.eot --> 有效。也许 TS 导入路径,但我不认为 SCSS 路径,它们总是必须相对于 dist 文件夹。刚刚犯了一个菜鸟错误,谢谢你的提示:)
    【解决方案2】:

    很难给你一个明确的答案,因为文件夹结构因项目而异,但看起来你需要使用 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"
    }
    

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-26
      • 2019-02-25
      • 2017-11-13
      • 2018-10-01
      • 2019-10-30
      • 1970-01-01
      相关资源
      最近更新 更多