加载字体时出现 Webpack 5 错误“未捕获错误:模块解析失败:意外字符‘@’”

aab*_*leh 6 sass webfonts font-face webpack sass-loader

添加sass-loaderwebpack 配置后,使用此节点模块@fontsource/roboto时出现构建错误

import "@fontsource/roboto"; // this is in index.tsx
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)

这是我的webpack 配置

import "@fontsource/roboto"; // this is in index.tsx
Run Code Online (Sandbox Code Playgroud)

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

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
Run Code Online (Sandbox Code Playgroud)

这是我的仓库

我究竟做错了什么?

Mar*_*nek 5

我在本地玩了你的存储库,似乎你的css文件没有被任何加载程序覆盖。我只需添加以下内容即可按预期运行构建:

        {
          test: /\.css$/i,                                                                                                                                                             
          use: ["style-loader", "css-loader", "sass-loader"],                                                                                                                          
        },  
Run Code Online (Sandbox Code Playgroud)

如果你遵守规则,你应该能够:

  • 优化loaders,让css文件不被跑通sass-loader
  • 改进一般测试正则表达式,使其覆盖所有 cass/scss/css 文件。

  • 这是涵盖 sass 和 css `/\.(scss|css)$/i` 的正确正则表达式。我只是从 [sass-loader](https://webpack.js.org/loaders/sass-loader/) 文档中复制了该正则表达式,而没有考虑它。谢谢! (2认同)