React Js,Web Pack - 无法将 css 文件从 node_module 导入 React 组件

React Js, Web Pack - not able to import css file from node_module into a react component

我在我的项目中使用 react-html5-camera-photo 节点模块从相机拍摄照片。该库要求使用 Camera 组件的组件导入 css 文件 (react-html5-camera-photo/build/css/index.css) 以设置捕获按钮的样式。

即使在我的 React 组件中添加 import 'react-html5-camera-photo/build/css/index.css' 之后,样式也没有应用,并且在通过检查元素 none 检查呈现的元素时,样式是从导入的 css 中应用的文件。

我尝试更改 webpack.config.js 设置但没有成功。

这是我的 webpack.config.js 设置

module: {
        rules: [
            {
                test: /react\-html5\-camera\-photo(.*?)\.css$/,
                use: [
                    { loader: "css-loader", options:{
                        modules: false
                    }}
                ]
            },
            {
                test: /\.(scss|css)$/,
                use: [
                    { loader: "style-loader" },
                    { loader: "css-loader",
                        options: {
                            modules: true,
                        }},
                    { loader: "sass-loader" }
                ]
            }
       ]
 }

但是使用此设置,css-loader 显示 Module build error

ERROR in ../node_modules/react-html5-camera-photo/build/css/index.css
Module build failed (from ../node_modules/css-loader/dist/cjs.js):
CssSyntaxError

(2:7) \node_modules\react-html5-camera-photo\build\css\index.css Unknown word

  1 | 
> 2 |       import API from "!../../../style-loader/dist/runtime/injectStylesIntoStyleTag.js";
    |       ^
  3 |       import domAPI from "!../../../style-loader/dist/runtime/styleDomAPI.js";
  4 |       import insertFn from "!../../../style-loader/dist/runtime/insertBySelector.js";
 @ ./components/OnsiteSituation/OnsiteSituation.tsx 84:0-54
 @ ./components/ServiceLead/ServiceLead.tsx 47:0-65 79:803-818
 @ ./App.tsx 33:0-63 45:370-381
 @ ./index.tsx 3:0-26 8:21-24

webpack 5.64.0 compiled with 1 error in 29408 ms

提前致谢,

我猜问题是 react-html5-camera-photo\build\css\index.css 由于两次满足规则而用 css-loader 处理了两次所以我认为你的问题可以通过 exclude react-html5-camera-photo 来自第二条规则如下:

[
    {
        test: /react\-html5\-camera\-photo(.*?)\.css$/,
        use: [
          // ... 
        ]
    },
    {
        test: /\.(scss|css)$/,
        // exclude your above rule to avoid processing twice
        exclude: /react\-html5\-camera\-photo(.*?)\.css$/,
        use: [
          // ...
        ]
    }
]