How to use @ font-face with webpack css-loader?

I am trying to import some font (e.g. Roboto) into my project using webpack, but none of them work.

My file structure is as follows:

+-src---fonts-+-Roboto---Roboto.ttf
|             |
|             +-fonts.css
|
+-webpack.config.js

My fonts.cssfile:

@font-face {
    font-family: 'Roboto';
    src: url(/Roboto/Roboto.ttf) format('truetype');
}

My webpack.config.jslooks like this:

//...
loaders: [
  {
    test: /\.css/,
    loaders: [
      'style-loader',
      `css-loader?${JSON.stringify({
        sourceMap: isDebug,
        localIdentName: isDebug ? '[name]_[local]_[hash:base64:3]' : '[hash:base64:4]',
        modules: true,
        minimize: !isDebug,
        importLoaders: 1
      })}`,
      'postcss-loader',
    ],
  },
  {
    test: /\.(png|jpg|jpeg|gif|svg|woff|woff2)$/,
    loader: 'url-loader',
  },
  {
    test: /\.(wav|mp3|eot|ttf)$/,
    loader: 'file-loader',
  },
],
//...

When I start webpack, the error does not appear. But the font was Robotonot loaded (the texts still represent the default font family, although I installed font-family: 'Roboto'in the text element).

What I tried:

  • Change the paths in the .cssfiles url()to the relative path: errors appeared:

    . /~/css-loader?{ "sourceMap":true, "localIdentName":[name][local][hash:base64:3] "," modules ":true," minimize ":false," importLoaders": 1}!./~/postcss-loader!./fonts/fonts.css : : Roboto/Roboto.ttf /Users/EnixCoda/projectName/fonts @./~/KSS- { "sourceMap": , "localIdentName": "[] [] [: base64: 3] "," ": ," "," importLoaders": 1}!./~/postcss-loader!./fonts/fonts.css 6: 135-163

- ?

+4

Source: https://habr.com/ru/post/1670950/


All Articles