Webpack @font-face relative path issue

可紊 提交于 2020-02-02 06:30:55

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/42497562/webpack-font-face-relative-path-issue

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!