ajmajmajma
ajmajmajma

Reputation: 14216

Webpack, trouble loading local fonts

I am having some issues loading my local fonts when using webpack. I have to host a few of my own fonts so I have a folder in /client/fonts with the fonts.

Right now, I am loading them into my production web pack build with && cp -R ./client/fonts dist/ in my npm script for the build process. I was trying to see if I could get the file-loader to do this for me so I would not have to rely on cp.

After a bit of googling, I tried to see if i could use the filer-loader for my needs like so (in my webpack production build) -

  ,{
      test: /\.(otf|eot|svg|ttf|woff|woff2)$/,
      loader: 'file-loader',
      query: {
        outputPath: 'fonts/'
      }
    }

However, when I run the build task I see no fonts imported. I am not sure what I am doing wrong here. For reference my webpack entry/output look like so :

  entry: {
    js: [
        path.join(__dirname, 'client/app.jsx')
    ],
    vendor: [
      'react',
      'react-dom',
      'lodash',
      'react-redux',
      'redux'
    ]
},
output: {
    path: path.join(__dirname, '/dist/'),
    filename: 'bundle.min.js',
    publicPath: '/'
},

And for the css (scss), I am using a loader like so -

    ,{
        test: /\.scss$/,
        loader: ExtractTextPlugin.extract('style', 'css!postcss!sass')
    },

and imported in my base.scss I have a _fonts.scss , which right now just looks like so :

  // Custom fonts
@font-face {
  font-family: 'SharpGroteskBook25';
  src: url('/fonts/sharpgrotesk/SharpGroteskBook25.eot');
  src: url('/fonts/sharpgrotesk/SharpGroteskBook25.eot?#iefix') format('embedded-opentype'),
  url('/fonts/sharpgrotesk/SharpGroteskBook25.woff') format('woff'),
  url('/fonts/sharpgrotesk/SharpGroteskBook25.ttf') format('truetype'),
  url('/fonts/sharpgrotesk/SharpGroteskBook25.svg#SharpGroteskBook25') format('svg');
  font-weight: normal;
  font-style: normal;
}

I am not sure what I am doing wrong here to get my fonts to load on my prod server. When I look at the live server I am not seeing the fonts being loaded in the prod task (getting a Failed to decode downloaded font error). Any idea how to resolve this issue? I would prefer webpack to load this than using a cp command. Thanks!

Upvotes: 1

Views: 811

Answers (1)

Michael Jungo
Michael Jungo

Reputation: 32972

The css-loader, which handles the imports and url, does not translate URLs that start with a /, therefore your file-loader won't be applied either.

The solution is to use relative paths for the imports if you want them to be processed by webpack. Note that CSS has no special syntax for relative imports so the following are equivalent:

url('fonts/sharpgrotesk/SharpGroteskBook25.eot')
url('./fonts/sharpgrotesk/SharpGroteskBook25.eot')

If you want them to be resolved just like a module, webpack offers the possibility to start the import path with a ~, as shown in the css-loader Readme.

Upvotes: 4

Related Questions