将CSS文件导入样式组件

dke*_*kez 5 reactjs quill styled-components

有没有一种方法可以将CSS文件导入样式化的组件中?

我的依赖之一,React Quill Editor,可以通过将其CSS导入为基础并在其之上进行更改来实现主题化。我所有的组件都是样式化的组件,我想将CSS本地化为JS组件,而不是将CSS作为“全局”样式导入。

现在,我要以以下形式将其CSS复制到我自己的文件中。

我在下面写了一个简短的例子。

/** 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;
`
Run Code Online (Sandbox Code Playgroud)

我宁愿导入在样式化组件范围内引用其CSS文件而不是对其进行复制。

如果我这样做import ReactQuillCSS from 'react-quill/dist/quill.snow.css';,由于该css-loader插件,它仍将在全球范围内应用我的CSS 。

最好,丹尼尔

小智 7

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

/** 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;

Run Code Online (Sandbox Code Playgroud)

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

添加!!到请求将禁用配置中指定的所有加载程序


for*_*d04 7

您可以添加模块规则以将样式从 CSS 文件本地导入到样式化组件中。

例如,从原始字符串导入所有第三方.css文件,其他文件照常导入:node_modules

// webpack.config.js
const config = {
  module: {
    rules: [
      {
        test: /\.css$/,
        use: ["style-loader", "css-loader"], // load project styles via style-loader
        exclude: /node_modules/, 
      },
      {
        test: /\.css$/,
        use: ["to-string-loader", "css-loader"], // use to-string-loader for 3rd party css
        include: /node_modules/,
      },
      // ...
    ],
  },
  // ...
}
Run Code Online (Sandbox Code Playgroud) 用法:
import styled from 'styled-components';
import ReactQuill from 'react-quill';
import ReactQuillCSS from 'react-quill/dist/quill.snow.css' // no custom webpack syntax

const StyledReactQuill = styled(ReactQuill)`
    ${ReactQuillCSS}
    // ... other styles
`
Run Code Online (Sandbox Code Playgroud)

to-string-loader如果尚未使用,请不要忘记安装。


这比 @jonathanhculver 的解决方案有一些优点:

  • 一个中央配置文件决定如何处理.css文件
  • 遵循 Webpack 的建议:

    尽可能使用module.rules ,因为这将减少源代码中的样板文件,并允许您在出现问题时更快地调试或定位加载程序。文档

  • 避免 ESLint 错误 - 查看Codesandbox演示

  • css-loader仍然可以解析@importurl()对于外部 CSS 文件,raw-loader不会


小智 -1

据我所知,没有办法在范围内导入常规 CSS。到目前为止,我将样式组件与库中的 CSS 相结合的方式是在 jsx.js 文件中为您自己的样式组件指定一个 className。

const MyStyledComponent = styled(ComponentFromLibrary)`
    color: red;
`;


// and in the render function

return (
    <MyStyledComponent className="libraryClassname" />
);
Run Code Online (Sandbox Code Playgroud)

另一个例子可以在官方文档中找到: https://www.styled-components.com/docs/advanced#existing-css

如果 editorCSS 只是您想要应用于组件的样式字符串,那么您所提议的内容将会起作用。