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

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

我添加后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

这是我的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",
      },
    ],
  },

如果我像这样从配置中删除 sass-loader,则构建成功(但我无法在我的项目中使用 sass 文件)

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

Here is my repo

我做错了什么?

我在本地玩过你的 repo,你的 css 文件似乎没有被任何加载器覆盖。我按预期获得了构建 运行ning,只需添加:

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

如果您玩弄规则,您应该能够:

  • 优化加载程序,因此 css 文件不会 运行 到 sass-loader
  • 改进通用测试正则表达式,使其涵盖所有 cass/scss/css 个文件。