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

Time:11-15

I'm using the react-html5-camera-photo node module in my project to take a photo from the camera. The library requires the component using the Camera component to import a css file (react-html5-camera-photo/build/css/index.css) to style capture buttons.

Even after adding import 'react-html5-camera-photo/build/css/index.css' into my react component, the styles are not applied and on checking the rendered elements through inspect element none of the styles are applied from the imported css file.

I tried changing my webpack.config.js settings but had no success.

Here are my webpack.config.js settings

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" }
                ]
            }
       ]
 }

But with this setting, the css-loader shows 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

Thanks in advance,

CodePudding user response:

I'm guessing the issue is react-html5-camera-photo\build\css\index.css was processing with css-loader twice due to meeting the rules twice so I think your issue can be sorted out by just exclude react-html5-camera-photo from the 2nd rule as following:

[
    {
        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: [
          // ...
        ]
    }
]
  • Related