Yu Mad
Yu Mad

Reputation: 878

Webpack: How to use CSS-modules and imported CSS from outside libraries?

I am using css-modules in my react application, however when I try to import outside files in .js files, I cannot import them globally because I cannot wrap them in a :global block, and webpack interprets them as styles meant to be used as objects.

How do I import CSS files as global CSS from external libraries? This is CSS that is supposed to match imported plugins.

e.g.in src/index.js

import 'draft-js/dist/Draft.css';
//cannot wrap in a :global block since it is imported
import 'react-responsive-carousel/lib/styles/carousel.min.css'; 
// is wrapped in a :global {...} block, so it works
import './styles/app.css'; 

Webpack configuration, from Create-React-App

test: /\.css$/,
loader: [
  require.resolve('style-loader'),
  {
   loader: require.resolve('css-loader'),
   options: {
     importLoaders: 1,
     modules: true,
     minimize: true,
    },
   },
    'postcss-loader'
]

Upvotes: 4

Views: 1938

Answers (1)

bschnelle
bschnelle

Reputation: 242

One option is to have two separate rules for src styles and node_modules styles and only set modules to true in your src config. It should look similar to below (I didn't test this) - the important options are include and exclude and to remove modules from the rule that applies to node_modules.

{
    test: /\.css$/,
    exclude: /node_modules/,
    loader: [
        require.resolve('style-loader'),
        {
            loader: require.resolve('css-loader'),
            options: {
                importLoaders: 1,
                modules: true,
                minimize: true,
            },
        },
        'postcss-loader'
    ]
},
{
    test: /\.css$/,
    include: /node_modules/,
    loader: [
        require.resolve('style-loader'),
        {
            loader: require.resolve('css-loader'),
            options: {
                importLoaders: 1,
                minimize: true,
            },
        },
        'postcss-loader'
    ]
}

Upvotes: 3

Related Questions