Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Webpack @font-face relative path issue

I have an issue with loading the fonts using a relative path in an angular2 application.

In app.ts I have these two imports

import '../../../public/css/fonts.less';
import '../../../public/css/main.less';

Inside the fonts.less I have this @font-face declaration:

@font-face {
    font-family: 'Montserrat';
    src: url('/public/fonts/Montserrat/Montserrat-Regular.eot'); /* IE9 Compat Modes */
    src: url('/public/fonts/Montserrat/Montserrat-Regular.eot?#iefix') format('embedded-opentype'), /* IE6-IE8 */
         url('/public/fonts/Montserrat/Montserrat-Regular.ttf') format('truetype'), /* Safari, Android, iOS */
         url('/public/fonts/Montserrat/Montserrat-Regular.svg#Montserrat-Regular') format('svg'); /* Legacy iOS */
    font-style: normal;
    font-weight: normal;
    text-rendering: optimizeLegibility;
}

And this works fine. But if I try to change the path to relative e.g.

url('../../fonts/Montserrat/Montserrat-Regular.eot');

I am getting this error:

ERROR in ./~/css-loader!./~/less-loader!./public/css/fonts.less Module not found: Error: Cannot resolve 'file' or 'directory' ../fonts/Montserrat/Montserrat-Regular.eot in [...] @ ./~/css-loader!./~/less-loader!./public/css/fonts.less 6:85-138 ERROR in ./public/css/fonts.less Module build failed: ModuleNotFoundError: Module not found: Error: Cannot resolve 'file' or 'directory' ../fonts/Montserrat/Montserrat-Regular.eot in [...]

Someone knows what can be the problem ?

P.S. I need to use relative paths for a reason.

like image 819
mkolev Avatar asked Oct 17 '22 16:10

mkolev


1 Answers

There is no particular reason for using relative paths in webpack. You can use webpack aliases to get rid of this necessity. Properly used aliases can resolve a lot of issues, including this one. Just specify an alias for your css and fonts directory:

resolve: {
  alias: {
    styles: path.resolve(__dirname, 'public/src'),
    fonts: path.resolve(__dirname, 'public/fonts')
  }
}

and then, import the modules using aliases:

import '~styles/fonts.less';
import '~styles/main.less';

and in your font face:

src: url('~fonts/Montserrat/Montserrat-Regular.eot'); 

I personally tend to avoid using relative paths in my webpack-built projects. The reason is that it is much more cleaner and readable, it prevents from problems that may arise with mixing the relative paths in different places that are dependent on each other. As a result, you have a central place where you define your paths and let the webpack resolve the relative paths for you.

like image 118
Adam Wolski Avatar answered Oct 21 '22 06:10

Adam Wolski