javascriptcssfontswebpackwebpack-file-loader

What's the correct way to load .otf font files in webpack?


What is the appropriate way to load .otf font files when using webpack? I have made several attempts to include a rule in my webpack.config.js, without any success, based on many examples I've seen along the lines of the following:

{ test: /\.(eot|svg|ttf|otf|woff)$/, use: 'file-loader' }
//or
{ test: /\.(eot|svg|ttf|otf|woff)$/, use: 'url-loader' }
//or
{ test: /\.(ttf|eot|svg|woff(2)?)(\?[a-z0-9=&.]+)?$/, use: 'file-loader' }
//...etc

I've set up in my webpack.config.js the following for other file types, which are working successfully:

module.exports = {
    //...
      module: {
        rules: [
          { test: /\.(js)$/, use: 'babel-loader' },
          { test: /\.css$/, use: [ 'style-loader', 'css-loader' ]},
          { test: /\.(jpe?g|png|gif|svg|xml)$/i, use: 'file-loader'}
        ]
      },
    //...
}

Despite my various attempts to add another rule/case for .otf files, I always get the following error:

Module parse failed: .../fonts/[name-of-my-font].otf Unexpected character ' ' (1:4) You may need an appropriate loader to handle this file type.

I've added the .otf file in a fonts folder in my root directory, and in my index.css I have:

@font-face {
  font-family: 'name-of-my-font';
  src: url('fonts/name-of-my-font.otf'),
  format('opentype');
}

Has anyone experienced a similar problem and found a solution for this?

Per comment request for more of my webpack.config.js file, here is my entire webpack.config.js:

var path = require('path');
var HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
  entry: './app/index.js',
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'index_bundle.js',
    publicPath: '/'
  },
  module: {
    rules: [
      { test: /\.(js)$/, use: 'babel-loader' },
      { test: /\.css$/, use: [ 'style-loader', 'css-loader' ]},
      { test: /\.(jpe?g|png|gif|svg|xml)$/i, use: 'file-loader' }
    ]
  },
  devServer: {
    historyApiFallback: true,
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: 'app/index.html'
    })
  ]
};

Solution

  • I added

      {    
        test: /\.(woff|woff2|eot|ttf|otf)$/,
        loader: "file-loader"
      }
    

    to my webpack.config.js. I think I needed to explicitly link the types to the file-loader. I was using the default VS2017 Angular project.