将 CSS 文件导入样式化组件 [英] Import CSS File to Styled Component

查看:45
本文介绍了将 CSS 文件导入样式化组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法将 CSS 文件导入到样式组件中?

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

我的一个依赖项 React Quill Editor 可以通过导入其 CSS 作为基础进行主题化并在其上应用更改.我的所有组件都是样式组件,我希望将 CSS 本地化为 JS 组件,而不是将 CSS 作为全局"样式导入.

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.

现在我已经开始按照以下形式将他们的 CSS 复制到我自己的文件中.

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;
`

我更愿意在样式组件的范围内导入引用他们的 css 文件,而不是复制它.

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

如果我 import ReactQuillCSS from 'react-quill/dist/quill.snow.css'; 由于 css-loader 它仍然会全局应用我的 css插件.

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.

最好的,丹尼尔

推荐答案

你可以使用 raw-loader 加载 quill.snow.css 样式表,然后将其包含在您的样式组件中.

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;

根据 raw-loader 文档,您可以使用 !! 来防止通过 css-loader 全局添加样式

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

这篇关于将 CSS 文件导入样式化组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆