Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Webpack can't load fonts (ttf)

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-light.ttf
│   └── /A-bold.ttf
│  
├── /styles/
│   ├── /base/
│   │   └── /__base.scss
│   └── styles.scss
│ 
├── app.jsx
└── webpack.config.js

_base.scss:

@font-face {
  font-family: "A";
  font-style: normal;
  font-weight: 400;
  src: url("../../fonts/A.ttf") format("truetype");
}

@font-face {
  font-family: "A";
  font-style: normal;
  font-weight: 800;
  src: url("../../fonts/A-bold.ttf") format("truetype");
}
@font-face {
  font-family: "A";
  font-style: normal;
  font-weight: 300;
  src: url("../../fonts/A-light.ttf") format("truetype");
}
body {
  font-family: A, Helvetica, Arial, sans-serif;
}

_base.scss is imported by styles.scss and styles.scss is imported in app.jsx.

My webpack config looks like this:
webpack.config.js

const path = require('path');
const webpack = require('webpack');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const StyleLintPlugin = require('stylelint-webpack-plugin');

process.env.NODE_ENV = process.env.NODE_ENV || 'development';
console.log(process.env.NODE_ENV);
if (process.env.NODE_ENV === 'development') {
  require('dotenv').config({path: '.env.development'});
}

module.exports = env => {
  const isProduction = env === 'production';
  const CSSExtract = new ExtractTextPlugin('styles.css');

  return {
    entry: ['babel-polyfill', './src/app.jsx'],
    output: {
      path: path.join(__dirname, 'public', 'dist'),
      filename: 'bundle.js'
    },
    resolve: {
      extensions: ['.js', '.jsx', '.json', '.css', '.scss']
    },
    module: {
      rules: [
        {
          exclude: /(node_modules|bower_components)/,
          test: /\.jsx?$/,
          use: ['babel-loader', 'eslint-loader']
        },
        {
          test: /\.s?css$/,
          use: CSSExtract.extract({
            use: [
              {
                loader: 'css-loader',
                options: {
                  sourceMap: true
                }
              },
              {
                loader: 'sass-loader',
                options: {
                  sourceMap: true
                }
              }
            ]
          })
        },
        {
          test: /\.(png|jpg|svg)$/,
          use: {
            loader: 'url-loader'
          }
        },
        {
          test: /\.(ttf|eot|woff|woff2)$/,
          loader: 'file-loader',
          options: {
            name: 'fonts/[name].[ext]'
          }
        }
      ]
    },
    plugins: [
      CSSExtract,
      new webpack.DefinePlugin({
        'process.env.API_AUTH_TOKEN': JSON.stringify(process.env.API_AUTH_TOKEN),
        'process.env.API_EMAIL': JSON.stringify(process.env.API_EMAIL),
        'process.env.API_PASSWORD': JSON.stringify(process.env.API_PASSWORD)
      }),
      new StyleLintPlugin({})
    ],
    devtool: isProduction ? 'source-map' : 'inline-source-map',
    devServer: {
      overlay: {
        warnings: true,
        errors: true
      },
      contentBase: path.join(__dirname, 'public'),
      historyApiFallback: true,
      publicPath: '/dist/'
    }
  };
};

However Webpack fails to compile.

Error:

./src/styles/styles.scss Module build failed: ModuleNotFoundError: Module not found: Error: Can't resolve '../../fonts/A.ttf'

Any help will be appreciated!

like image 448
greenN Avatar asked Apr 17 '18 11:04

greenN


People also ask

How do I import a font into Webpack?

If you have some local font files of your own, place them in a font directory within src and reference them within . style. scss using @font-face as you normally would—webpack will see that you're referencing a font file and run it through the file-loader like it did with Font Awesome and Google Fonts.

How do I add fonts to Webpack 5?

Webpack Font Setup First, put your font files into one folder of your projects application. For instance, your src/ folder may have a folder assets/ which has a folder fonts/. }; It's quite similar to setting up images with Webpack.


1 Answers

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]',
          },
        },
      ]
    }
  ]
}
like image 98
suntzu Avatar answered Sep 18 '22 14:09

suntzu