Webpack 5 with SASS loader and MiniCSSExtractPlugin doesn't move fonts

Viewed 600

I'm fairly new to Webpack 5, while my build is almost working, my fonts are not being transfered to my /dist folder. I include the fonts in my main.scss file (see below)

Am I missing something with my current config?

folder structure

- src
    - assets
        - sass
        - fonts

src/assets/sass/main.scss

@font-face {
    font-family: 'P22MackinacMedium';
    src: url('../fonts/p22-mackinac-medium.eot');
    src: url('../fonts/p22-mackinac-medium.eot?#iefix') format('embedded-opentype'),
             url('../fonts/p22-mackinac-medium.woff2') format('woff2'),
         url('../fonts/p22-mackinac-medium.woff') format('woff'),
         url('../fonts/p22-mackinac-medium.ttf') format('truetype'),
         url('../fonts/p22-mackinac-medium.svg#youworkforthem') format('svg');
    font-weight: normal;
    font-style: normal;
}

webpack.config.js

const path = require('path');

const HtmlWebpackPlugin = require('html-webpack-plugin')
const MiniCssExtractPlugin = require("mini-css-extract-plugin");

module.exports = {
    mode: 'development',
    entry: './src/index.js',
    plugins: [new MiniCssExtractPlugin(), new HtmlWebpackPlugin({
        template: 'src/index.html'
    })],
    output: {
        filename: '[name]-[contenthash].js',
        chunkFilename: '[name]-[chunkhash].js',
        path: path.resolve(__dirname, 'dist'),
    },
    optimization: {
        splitChunks: {
            chunks: 'all',
            cacheGroups: {
                commons: {
                    test: /[\\/]node_modules[\\/]/,
                    name: 'vendors',
                    chunks: 'all',
                },
            },
        }
    },
    module: {
        rules: [
            {
                test: /\.css$/,
                use: [
                    // Creates `style` nodes from JS strings
                    "style-loader",
                    // Translates CSS into CommonJS
                    "css-loader",
                ],
            },
            {
                test: /\.scss$/,
                use: [
                    MiniCssExtractPlugin.loader, {
                        loader: 'css-loader',
                        options: { url: false }
                    },
                    'sass-loader'
                ],
            },
            {
                test: /\.(woff|woff2|eot|ttf|otf)$/i,
                type: 'asset/resource',
              },
        ],
    },
    devServer: {
        static: './dist',
    },
};
1 Answers

As far as I can see this should be working out of the box, like you wrote it, since webpack 5 is using new Assets management. But, since it is not working for you, you can still try to use url-loader. Like this:

  {
    test: /\.(woff|woff2|eot|ttf|otf)$/i,
    use: {
      loader: 'url-loader',
    },
  },

Or you could try 'asset/inline' before installing url loader.

Related