Search code examples
webpackfontslesswebpack-file-loaderless-loader

How to load fonts from LESS file with Webpack 5?


I am using Webpack 5 and loading fonts and other styles from a .less file. However, the fonts/styles do not seem to be loading, and I'm trying to figure out why.

bootstrap.less

@import (less) '~bootstrap/dist/css/bootstrap.css';

@font-face {
  font-family: 'Gibson';
  src: url('~fonts/gibson/gibson-semibold.otf') format('opentype');
  font-weight: bold;
}

@font-face {
  font-family: 'Gibson';
  src: url('~fonts/gibson/gibson-regular.otf') format('opentype');
  font-weight: normal;
}

Config

{
  module: {
    rules: [
      {
        test: /\.otf$/,
        include: path.resolve(__dirname, './src/fonts'),
        use: {
            loader: 'file-loader',
            options: {
                name: '[name].[ext]',
                outputPath: 'fonts/',
                esModule: false
            },
        },
    },
      {
        test: /\.less$/,
        use: [
          { loader: 'style-loader' },
          {
            loader: 'css-loader',
            options: {
              url: false,
            },
          },
          { loader: 'less-loader' },
        ],
      },
      {
        test: /\.css$/,
        use: [
          { loader: 'style-loader' },
          {
            loader: 'css-loader',
            options: {
              modules: true,
              url: false,
            },
          },
        ],
      },
    ],
  },
};

I'm using React on Rails with Webpacker, and bootstrap.css is located under node_modules/bootstrap/dist/css. the two .otf font files are located under public/packs/assets/fonts/gibson and also under app/assets/fonts/gibson.

What am I missing? I can see that webpack is recognizing the font files at least:

...
odules by path ./app/assets/ 579 KiB
    modules by path ./app/assets/stylesheets/application/*.less 76.7 KiB 62 modules
    modules by path ./app/assets/stylesheets/*.less 502 KiB 4 modules
    modules by path ./app/assets/images/ 362 bytes 4 modules
    modules by path ./app/assets/fonts/gibson/*.otf 173 bytes 2 modules
webpack 5.68.0 compiled successfully in 7608 ms

However, I do not see the fonts loaded on the site itself. In my main application.jsx I have imported like so: import 'stylesheets/bootstrap.less';


Solution

  • I was able to fix this issue by adding:

    *{font-family:Gibson;}

    to my bootstrap.less file. I'm really uncertain this is the best way to do this, but it does work.