简体   繁体   中英

Angular 6 import SCSS from node_modules with assets

I currently have a library which exports some SCSS with paths to fonts laying in a subfolder.

  • nodemodules/library/fonts/font.scss
  • font files eg in nodemodules/library/fonts/bold/xyz.eot

With the SCSS looking like the following in my font.scss in the node_modules folder

@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");
}

The file will be imported in the angular project in the main.scss file in the src-folder. The folder will be copied from the angular build to assets with the following setting

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

My question is how the $font-path should look like, or what i need to fix the problem. What i already tried and didn't work (always cant resolve the 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)

The problem is that CSS-Loader will always check the urls, when building the app it always tries to resolve the path to src/assets which obviously has no files in it, because they will only get copied to the destination folder (from the cli-config).

Is there any solution?

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

When your app builds default all files will be in your dist folder. It will look something like this

  • assets
  • index.html
  • bunch of js files and other

You won't have an src folder on root.

Absolute path would be /assets/fonts/bold/xyz.eot

I think relative path would be ./nodemodules/library/fonts/bold/xyz.eot

It will be hard to give you a definitive answer, since folder structure varies from project to project, but it looks like you need to use --deploy-url flag from Angular CLI.

Here's an excerpt from my project's 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"
}

In my case, all the fonts are mixed with main Angular CLI generated bundles in dist folder. The styles.css file is in there as well and I have no problems with broken paths.

Again, like I said, your folder structure may differ, but deploy-url flag is a way to go.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM