Webpack sass-loader: How to correctly use fonts?

sandrooco picture sandrooco · May 30, 2017 · Viewed 12.3k times · Source

So I have the following font setup:

$font-path: '~@/assets/fonts/';
@font-face {
    font-family: 'mainFont';
    font-weight: 300;
    font-style: normal;
    src: url('#{$font-path}mainFont/mainFont.eot') format('eot'),
    url('#{$font-path}mainFont/mainFont.woff2') format('woff2'),
    url('#{$font-path}mainFont/mainFont.woff') format('woff'),
    url('#{$font-path}mainFont/mainFont.ttf') format('truetype'),
    url('#{$font-path}mainFont/mainFont.svg#mainFont') format('svg');
}

The build (with vue.js webpack btw) works as expected. The app won't be able to load the fonts though. the src urls point to the wrong directory. When changing the $font-path to the folder relative to the output file (as suggested), the build fails because it can't find the fonts.

Answer

Pavel Denisjuk picture Pavel Denisjuk · May 31, 2017

Use file-loader and in your rules use something like this (example taken from my project):

{
    test: /\.(woff2?|ttf|otf|eot|svg)$/,
    exclude: /node_modules/,
    loader: 'file-loader',
    options: {
        name: '[path][name].[ext]'
    }
}

This will copy the files into your build folder and will inject the correct URLs to those files in your CSS.

Second thing is to add resolve-url-loader to your scss rule:

{
    test: /\.scss$/,
    use: ExtractTextPlugin.extract({
        fallback: 'style-loader',
        use: ['css-loader', 'resolve-url-loader', 'sass-loader?sourceMap']
    })
}