VVV
VVV

Reputation: 7603

Importing CSS file in React - Webpack / Inline styles

I was assigned a project where I need to stylize an application built with React + Wepback.

When I look at the output in the inspector element, I can see that most elements have a dynamically created class that looks like this: css-18s71b6

Looking at the styles, it's a stylesheet that's imported from a node module... Microsoft Frabric to be exact.

I'm able to add my custom stylesheet so that I can add my className to the elements but the problem I'm having is that my styles are never considered because React's dynamic css rule always has priority.

The only way to overcome this is by putting !important in all my css rules which doesn't make sense.

My guess is that I need to tell React + Webpack to use my stylesheet when compiling the dynamic inline css styles or to disable dynamic classes.

I'm completely new to React + Webpack. I've been working on this for hours, reading and testing but never found any solution. Any input is appreciated.

For what it's worth, my webpack.bable.js file looks like this

module: {
    loaders: [{
      test: /\.js$/, // Transform all .js files required somewhere with Babel
      loader: 'babel-loader',
      exclude: /node_modules/,
      query: options.babelQuery,
    }, {
      test: /\.css$/,
      include: /node_modules/,
      loaders: ['style-loader', 'css-loader'],
    }, 
    [... more stuff ...]
}

Upvotes: 1

Views: 1728

Answers (1)

VVV
VVV

Reputation: 7603

After countless hours, I finally found the answer and am posting it in case other people have the same problem.

The problem is that in the config file, when you include: /node_modules/ it won't include your custom CSS styles. You need a separate loader to accomplish this.

My final webpack config looks like this

    [...] {
      // Preprocess our own .css files
      test: /\.css$/,
      exclude: /node_modules/,
      use: ['style-loader', 'css-loader'],
    },{
      test: /\.css$/,
      include: /node_modules/,
      loaders: ['style-loader', 'css-loader'],
    } [...]

Notice that the first rule excludes node_modules and the second one includes /node_modules/

For more information on the topic, visit this forum post on Github.

Upvotes: 2

Related Questions