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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With