Webpack can't load fonts (ttf)

前端 未结 4 1654
心在旅途
心在旅途 2021-02-20 05:56

Currently I have 3 fonts that I want to add to my React project:a, a light, a bold.
My file structure:

/src
├── /fonts/
│   ├── /A.ttf
│   ├── /A-         


        
相关标签:
4条回答
  • 2021-02-20 06:23

    As of webpack 5 you can use built-in asset modules instead. From the guide here, add this to module.rules to load .ttf files:

    {
      test: /\.(woff|woff2|eot|ttf|otf)$/i,
      type: 'asset/resource',
    },
    
    
    0 讨论(0)
  • 2021-02-20 06:33

    Webpack requires a font loader to load font files present in your project. you are using a file loader to load fonts. Change

    {
          test: /\.(ttf|eot|woff|woff2)$/,
          loader: 'file-loader',
          options: {
          name: 'fonts/[name].[ext]'
     }
    

    to

     {
          test: /\.ttf$/,
          use: [
            {
              loader: 'ttf-loader',
              options: {
                name: './font/[hash].[ext]',
              },
            },
          ]
      }
    

    by installing a font loader in your project like TTF Loader from NPM.

    0 讨论(0)
  • 2021-02-20 06:36

    Using 'ttf-loader' from npm worked perfectly for me.

    https://www.npmjs.com/package/ttf-loader

    module: {
      rules: [
        {
          test: /\.ttf$/,
          use: [
            {
              loader: 'ttf-loader',
              options: {
                name: './font/[hash].[ext]',
              },
            },
          ]
        }
      ]
    }
    
    0 讨论(0)
  • 2021-02-20 06:42

    Prefix the font path with ~, to tell Webpack that this is not a relative import https://github.com/webpack-contrib/sass-loader#imports

    0 讨论(0)
提交回复
热议问题