2

I'm a newbie in webpack. I try connecting font using webpack and sass-loader, but, as a result, the fonts are copied to the /dist folder with hashes instead of names and are also included in the final CSS file. How can I change this behavior and display the correct filenames?

webpack.config.js

const MiniCss = require("mini-css-extract-plugin");

module.exports = {
    mode: 'development',
    entry: './src/app.js',
    output: {
        path: __dirname + '/dist',
        filename: '[name].js',
        clean: true
    },
    plugins: [
        new MiniCss()
    ],
    module: {
        rules: [
            {
              test: /\.scss$/,
              exclude: /node_modules/,
              use: [
                MiniCss.loader,
                "css-loader",
                "sass-loader",
              ],
            },
            {
                test: /\.(ttf|woff|woff2)$/,
                exclude: /node_modules/,
                use: [
                  {
                      loader: 'file-loader',
                      options: {
                          name: '[name].[ext]',
                          outputPath: 'fonts/'
                    }
                  }
                ]
            }
        ],
    },
}

dist folder

├── 11022a6635d6693e063c.ttf
├── 8c84d95d5f3e9e56336a.ttf
├── a620d73f65c1c92f51f0.ttf
├── fonts
│   ├── Roboto-Light.ttf
│   ├── Roboto-Regular.ttf
│   └── Roboto-Thin.ttf
├── main.css
└── main.js

output main.css

@font-face {
  src: url(11022a6635d6693e063c.ttf) format("ttf");
  font-family: "Roboto";
  font-weight: 100;
}
@font-face {
  src: url(8c84d95d5f3e9e56336a.ttf) format("ttf");
  font-family: "Roboto";
  font-weight: 300;
}
@font-face {
  src: url(a620d73f65c1c92f51f0.ttf) format("ttf");
  font-family: "Roboto";
  font-weight: 400;
}
h1 {
  font-family: "Roboto", sans-serif;
}
Karl Hill
  • 12,937
  • 5
  • 58
  • 95
poorfrog
  • 21
  • 2

1 Answers1

5

Found the answer here. The key is to use webpack's asset modules instead of file-loader:

{
  test: /\.(ttf|woff|woff2)$/,
  exclude: /node_modules/,
  type: 'asset/resource',
  generator: {
    filename: 'fonts/[name][ext]'
  }
}