Use font-face with webpack encore Use font-face with webpack encore symfony symfony

Use font-face with webpack encore


I gave up doing it without plugins or loader, I tried the file loader : didn't work, I tried the copy plugin : success.

webpack.config.js

var Encore = require('@symfony/webpack-encore');var CopyWebpackPlugin = require('copy-webpack-plugin');Encore    ...    .addPlugin(new CopyWebpackPlugin([        { from: './assets/fonts', to: 'fonts' }    ]))    /*.addLoader({        test: /\.(eot|svg|ttf|woff)$/,        use: [{            loader: 'file-loader',            options: {                name: '[path][name].[ext]',                context: './assets',            }        }]    })*/    ...;module.exports = Encore.getWebpackConfig();

the css:

@font-face {    font-family: "myfont";    src: url('/build/fonts/myfont.eot'); /* IE9 Compat Modes */    src: url('/build/fonts/myfont.eot?#iefix') format('embedded-opentype'), /* IE6-IE8 */         url('/build/fonts/myfont.woff') format('woff'), /* Modern Browsers */         url('/build/fonts/myfont.ttf')  format('truetype'), /* Safari, Android, iOS */         url('/build/fonts/myfont.svg#myfont') format('svg'); /* Legacy iOS */}

Update for new versions of webpack encore :This answer wasn't working anymore after updating webpack encore.

Now, I could remove the CopyWebpackPlugin, and could instead refer to the fonts in the assets folder (webpack detects the urls and copy them in the build, and change the path all alone)

The CSS:

@font-face {    font-family: "myfont";    src: url('../fonts/myfont.eot'); /* IE9 Compat Modes */    src: url('../fonts/myfont.eot?#iefix') format('embedded-opentype'), /* IE6-IE8 */         url('../fonts/myfont.woff') format('woff'), /* Modern Browsers */         url('../fonts/myfont.ttf')  format('truetype'), /* Safari, Android, iOS */         url('../fonts/myfont.svg#myfont') format('svg'); /* Legacy iOS */}

Note that the svg version is put by webpack in an image folder, not font.


Another approach would to change how the font-files get saved.You can read more here https://github.com/symfony/webpack-encore/issues/282

Encore    .addLoader({        test: /\.(woff|woff2|eot|ttf|otf)$/,        use: [            {                loader: 'file-loader',                options: {                    outputPath: 'assets/dist/fonts/''                }            }        ]    })    .configureFilenames({        fonts: 'fonts/[name].[ext]'    })