Search code examples
webpackmaterial-designweb-componentcreate-react-appcss-modules

How to import existing stylesheet as CSS module using Webpack / create-react-app


Background: I'm building a Wordpress plugin (to be installed in multiple Wordpress instances) using React. The Wordpress instances may have different themes/custom stylesheets installed.

The plugin registers a shortcode with React; A post in Wordpress containing that shortcode [MyForm] instructs Wordpress to render a container div (with a well-known 'id') and to enqueue the script and stylesheet outputs from Webpack. So far so good.

I'm making use of the react-md component library which sets up various things (styling of input elements, headings, default fonts - etc).

At the moment I'm importing the stylesheet for react-md with

import 'react-md/dist/react-md.blue-green.min.css';

The problem I'm encountering is that some of the styles from react-md are being overwritten by the Wordpress theme.

I understand that create-react-app 2.x includes support for CSS modules. Can I make use of these to:

  1. Ensure my component gets more-specific selectors so that my styles / the styles from react-md are not overwritten
  2. Ensure my styles / the styles from react-md do not leak out onto the rest of the page.

NB: If necessary, I'm happy to eject from create-react-app and get my hands dirty with Webpack.


Solution

  • Using SASS to import the CSS file under a rule works, e.g.

    .my-form {
        @import url("https://fonts.googleapis.com/css?family=Roboto:300,400,500");
        @import url("https://fonts.googleapis.com/icon?family=Material+Icons");
    
        @import '~react-md/src/scss/react-md';
    }