将CSS文件导入Styled Component

15
有没有一种方法可以将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;
`

我更希望在styled组件的作用域内引用他们的css文件,而不是复制它。

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

最好的, 丹尼尔

7个回答

10
你可以使用raw-loader来加载quill.snow.css样式表,然后将其包含在你的styled组件中。
/** 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防止样式全局添加。引用:“将!!添加到请求中将禁用配置中指定的所有加载程序。”
返回结果:根据raw-loader的文档,您可以使用!!通过css-loader防止样式全局添加。引用:“将!!添加到请求中将禁用配置中指定的所有加载程序。”

你好,我该如何将 StyledReactQuill 作为带有子元素的 React 组件使用呢?类似于 <StyledReactQuill>{children}</StyledReactQuill> 这样的形式。如果我使用 styled.div`` ,结果是一个带有子元素的 React 组件,但是使用 styled(Quill)`` 却不行。 - Thami Bouchnafa

7

您可以添加一个模块规则,将CSS文件中的样式局部地导入到styled component中。

例如,将所有第三方.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/,
      },
      // ...
    ],
  },
  // ...
}

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
`

如果还没有使用,请不要忘记安装to-string-loader


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

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

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

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

  • css-loader仍然可以解析外部CSS文件的@importurl()raw-loader不能

1
为了实现这一点,您需要使用与css-loader不同的加载器。您可以编写一个不同的加载器,将其准备好供styled-components使用,而不是将其添加到全局样式表中。
如果您需要css-loader,则需要定义哪些css文件由其处理,哪些文件加载到styled-components中,这使得它在我看来不是非常实用。

0
在我的情况下,我使用的最简单的解决方案是不需要额外的加载器,只需进入CSS文件并复制粘贴美化版本即可。
例如,您有一个带有“body {background:red}”的“lib / dit / lib.min.css”。
然后只需将所有CSS复制到您的样式组件或全局样式组件样式中即可。
styled.div`
    body{
        background: red;
    }
`

❗️ 缺点:新版本的包可能会修改lib.css,因此您必须重复操作;lib CSS 复杂度高。

✅ 优点:无需额外的加载器;您可以直接重构lib.css。


0

这是我的做法:

代码

import React, { Component } from "react";
import ReactDOM from "react-dom";
import Styled from "styled-components";

const fetchStyles = () =>
  fetch(
    "https://gist.githubusercontent.com/bionicvapourboy/61d3d7a8546cb42e0e3194eb9505f48a/raw/5432218dd83320d53d1cbc2f230b81c765183585/style.css"
  ).then(response => response.text());

class App extends Component {
  state = {
    style: ""
  };

  componentDidMount() {
    fetchStyles().then(data => this.setState({ style: data }));
  }

  Wrapper = () => Styled.div`
    ${this.state.style}
  `;
  render() {
    const Wrapper = this.Wrapper();
    return (
      <div className="App">
        <Wrapper>
          <h1>Styled</h1>
        </Wrapper>
        <h1>Not Styled</h1>
        <h2>Start editing to see some magic happen!</h2>
      </div>
    );
  }
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

演示

https://codesandbox.io/s/yw7xmx6x3x


-1
据我所知,目前还没有一种仅限于范围的方式来导入常规CSS。到目前为止,我使用styled-components和来自库的CSS的方法是在JSX中为您自己的styled组件命名一个className。

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


// and in the render function

return (
    <MyStyledComponent className="libraryClassname" />
);

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

如果editorCSS只是一个你想应用于组件的样式字符串,那么你提出的方法是可行的。


-1

据我理解,styled-components 本质上只是模板字面量。

你唯一的问题应该是在将导入的 CSS 放入组件的 CSS 中时,它被定义为一个对象。你尝试过先将其转换为字符串吗?

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

const newCSS = editorCSS.toString();

export default Styled(ReactQuill)`
  ${newCSS}
`;

1
editorCSS.toString() 将返回 [object Object] - Hamid Mayeli

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接