Search code examples
cssfontswebpackwebpack-2

Font doesn't get loaded through webpack


Hello dear webpack community. I desperately try to load fonts using the file-loader I tried both of these rules:

{ test: /\.(woff|eot|svg|otf|ttf)$/i, loader: `file-loader`, options: {name:'fonts/[name].[ext]'}},
{ test: /\.(woff|eot|svg|otf|ttf)$/i, loader: `file-loader?name=fonts/[name].[ext]`},

however, unfortunately, the fonts don't get pulled when asked for them in the @font-face rule:

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

This is how my project structure looks like:

structure

This is the Webpack output:

webpack output

While fonts.less is loaded, I don't see any font getting loaded through the definition of src().

Thank you a lot for any hint in advance!

See the full config file here: https://gist.github.com/MartinMuzatko/2873b52fed204bd6e8aaaa94527e34a9


Solution

  • The problem is that you're using raw-loader to transform the output of the less-loader to JavaScript so that extract-text-webpack-plugin can use it.

    {
        test: /\.less$/, use: ExtractTextPlugin.extract(
            [
                {loader:'raw'},
                {loader:'less'}
            ]
        ),
    }
    

    The less-loader simply transforms the Less syntax to regular CSS. The url() won't be touched. The css-loader on the other hand treats them as imports that webpack will resolve. Only then your rules for the fonts will take effect. All you need to do is change your .less rule to use css-loader instead of raw-loader:

    {
        test: /\.less$/, use: ExtractTextPlugin.extract(
            [
                {loader:'css'},
                {loader:'less'}
            ]
        ),
    }