0

Project structure

/dev
-/fonts
-/css
  -/vendors
    -/fontawesome
      -/webfonts
/dist
-/my-project
  -/fonts

With file-loader for Webapck, I´m trying to compile all sass/scss with url path and moved all font files into dist/my-project/fonts/.

webpack.config.js

module.exports = env => {
    ...
    return{
        ...
        output: {
            path: path.resolve(__dirname, 'dist/'),
        },
        module: {
            rules: [
            {
                test: /\.(woff(2)?|ttf|eot|svg)(\?v=\d+\.\d+\.\d+)?$/,
                use: [
                    {
                        loader: 'file-loader',
                        options: {
                            name: '[name].[ext]',
                            outputPath: './my-project/fonts/',
                            context: './fonts/'
                        }
                    }
                ]
            },
            {
                test: /\.(woff(2)?|ttf|eot|svg)(\?v=\d+\.\d+\.\d+)?$/,
                use: [
                    {
                        loader: 'file-loader',
                        options: {
                            name: '[name].[ext]',
                            outputPath: './my-project/fonts/',
                            context: 'css/vendors/'
                        }
                    }
                ]
            }
            ]
        }
    }
}          

This config manage to copy files at the right place but in the css, I got this:

@font-face{
   font-family:'Font Awesome 5 Brands';
   font-style:normal;
   font-weight:normal;
   font-display:auto;
   src:url(my-project/fonts/fa-brands-400.eot); //<--instead of fonts/fa-brands-400.eot
   ...
}

So how to compile the right url font path in css files keeping this outPath ?

J.BizMai
  • 2,621
  • 3
  • 25
  • 49

1 Answers1

2

The solution is to use :

  • publicPath to compile path in css url font
  • outPath to move font files in the right directory

So...

{
    test: /\.(woff(2)?|ttf|eot|svg)(\?v=\d+\.\d+\.\d+)?$/,
    use: [
        {
            loader: 'file-loader',
            options: {
                name: '[name].[ext]',
                publicPath: './fonts/', //<--resolve the path in css files
                outputPath: './my-project/fonts/', //<-- path to place font files
                context: 'css/vendors/'
            }
        }
    ]
} 
J.BizMai
  • 2,621
  • 3
  • 25
  • 49