Search code examples
webpacksassfont-facewebfontssass-loader

Webpack 5 error "Uncaught Error: Module parse failed: Unexpected character '@'" when loading fonts


After I added sass-loader to my webpack configuration, I'm getting a build error when using this node module @fontsource/roboto

import "@fontsource/roboto"; // this is in index.tsx
Uncaught Error: Module parse failed: Unexpected character '@' (2:0)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
| /* roboto-cyrillic-ext-400-normal*/
> @font-face {
|   font-family: 'Roboto';
|   font-style: normal;
    at eval (index.css:1)
    at Object../node_modules/@fontsource/roboto/index.css (index.js:18)
    at __webpack_require__ (index.js:556)
    at fn (index.js:767)
    at eval (index.tsx:6)
    at Module../src/index.tsx (index.js:62)
    at __webpack_require__ (index.js:556)
    at index.js:1613
    at index.js:1617

Here is my webpack configuration

  module: {
    rules: [
      {
        test: /\.tsx?$/,
        use: "babel-loader",
        exclude: /node_modules/,
      },
      {
        test: /\.s[ac]ss$/i,
        use: ["style-loader", "css-loader", "sass-loader"],
      },
      {
        test: /\.(png|svg|jpg|jpeg|gif)$/i,
        type: "asset/resource",
      },
      {
        test: /\.(woff|woff2|eot|ttf|otf)$/i,
        type: "asset/resource",
      },
    ],
  },

The build succeeds if I remove sass-loader from the config like this (but then I can't use sass files in my project)

      {
        test: /\.css$/i,
        use: ["style-loader", "css-loader"],
      },

Here is my repo

What am I doing wrong?


Solution

  • I played with your repo locally, and seems your css files were not covered by any loaders. I got the build running as expected with just adding:

            {
              test: /\.css$/i,                                                                                                                                                             
              use: ["style-loader", "css-loader", "sass-loader"],                                                                                                                          
            },  
    

    if you play around with the rules, you should be able to either:

    • optimize loaders, so css files are not run through sass-loader
    • improve the general test regex so it cover all cass/scss/css files.