Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom font not taking effect using Webpack, Sass

I am using Webpack to bundle my Sass files then process them into CSS. I also have custom fonts that I include in my Sass file via the @font-face mixin.

I have a folder structure as follows:

MyAppFolder
├── app
│   ├── css
│   │   ├── _custom_font.scss
│   │   ├── _variables.scss
│   │   └── main.scss
│   ├── fonts
│   │   └── MyFont.otf
│   ├── images
│   │   └── home.png
│   ├── index.html
│   └── js
└── webpack.config.js

The webpack.config.js is as follows

^^^^ other config

loaders: [
  // SASS
  {
    test: /\.scss$/,
    loaders: ['style', 'css', 'sass']
  },

  // FONTS
  {
    test: /\.(otf|eot|svg|ttf|woff)/,
    loader: 'url-loader?limit=8192'
  }
]
....

_custom_font.scss is as follows:

@font-face {
  font-family: 'MyFont';
  src:  url('../fonts/MyFont.otf') format('otf');
}

main.scss is as follows:

body {
  font-family: 'MyFont';
}

Webpack goes away and builds everything fine. I can see its included the custom font file as in the webpack output I see the font file as an output file.

When viewing my web page I don't see the custom font applied. I see the css definition is correct but the font looks almost like Times New Roman. When I remove the definition from my Sass file it falls back to using Helvetica Neue. I have bootstrap so this is what I would expect.

like image 248
teddy777 Avatar asked Nov 09 '22 03:11

teddy777


1 Answers

Guess you have already found the answer somewhere. Anyway posting the answer for whoever is stuck here.

Resolve-url-loader helps. See https://github.com/bholloway/resolve-url-loader

Change your SCSS loader configs as below.

{
  test: /\.scss$/,
  loaders: ['style-loader', 'css-loader', 'resolve-url-loader', 'sass-loader?sourceMap']
}

Make sure the output.publicPath is correctly configured. In most cases, it should be /.

output: {
  publicPath: '/'
}
like image 200
Ryan Tsui Avatar answered Nov 15 '22 05:11

Ryan Tsui