Import CSS File to Styled Component

dankez picture dankez · Mar 17, 2018 · Viewed 11.8k times · Source

Is there a way to import a CSS file into a styled component?

One of my dependencies, React Quill Editor, is themeable by importing their CSS as a base and applying changes on top of it. All of my components are styled components, and I'd like to keep the CSS localized to the JS component rather than import the CSS as a 'global' style.

Right now I've take to copying their CSS into my own file in the following form.

I've written a brief example below.

/** editorCSS.js **/
import { css } from 'styled-components';
export default css`
/* copied CSS here */

.class-to-extend {
   color: green;
}
`


/** EditorComponent.js **/ 
import styled from 'styled-components';
import ReactQuill from 'react-quill';
import editorCSS from './editorCSS';

const StyledReactQuill = styled(ReactQuill)`
    ${editorCSS}
    /** Additional customization if necessary (e.g. positioning) */
`
export default StyledReactQuill;
`

I'd much rather import reference their css file in the scope of the styled component vs copying it.

If I do import ReactQuillCSS from 'react-quill/dist/quill.snow.css'; it will still apply my css globally due to the css-loader plugin.

Best, Daniel

Answer

jonathanhculver picture jonathanhculver · Nov 21, 2019

You could use raw-loader to load the quill.snow.css stylesheet and then include it in your styled component.

/** EditorComponent.js **/ 
import styled from 'styled-components';
import ReactQuill from 'react-quill';
import quillCSS from '!!raw-loader!react-quill/dist/quill.snow.css';

const StyledReactQuill = styled(ReactQuill)`
    ${quillCSS}
    /** Additional customization if necessary (e.g. positioning) */
`
export default StyledReactQuill;

Per the raw-loader docs, you can use !! to prevent the styles being added globally via css-loader

Adding !! to a request will disable all loaders specified in the configuration