Splitting Styled-Components into multiple files but export them as one file

半腔热情 提交于 2020-01-15 06:37:07

问题


When I was building my application, I didn't realize that I am going to end up with more than a hundred styled components. Consequently, I was putting them in the same file like this:

export const StyledTabs = styled(Tabs)`
  display: inline-flex !important;
  margin-left: 15% !important;
`;

export const StyledTab = styled(Tab)`
  display: inline-flex !important;
  margin-left: 0% !important;
  padding: 0 !important;
`;

... And the application imports them like this:

import { StyledTabs, StyledTitle } from "StyledComponents";

I want to split the StyledComponents.js file into multiple files by, for example, UI logic (header, footer, containers, etc..) but somehow, import them back into StyledComponents.js so I don't have to refactor the entire application.

Is something like this possible:

HeaderSC.js

export const StyledTabs = styled(Tabs)`
  display: inline-flex !important;
  margin-left: 15% !important;
`;

export const StyledTab = styled(Tab)`
  display: inline-flex !important;
  margin-left: 0% !important;
  padding: 0 !important;
`;

StyledComponents.js

import { StyledTabs, StyledTitle } from "../styling/HeaderSC";

..and then the app still referring to StyledTabs or any other styled component from StyledComponents.js file?


回答1:


You can create a folder StyledComponents and inside that create a default import file index.js, from which all your exports will be facilitated.

In the very same folder create different files for different components like StyledTabs.js and StyledTitle.js then index.js of the very same folder you can do

export StyledTab from './StyledTab';
export StyleTitle from './StyledTitle';

This way your import { StyledTab } from 'path/to/StyledComponents' will work flawlessly




回答2:


You can do it like following this steps.

1) You create folder Tabs

2) Inside Tabs folder you create index.js and styled.js files.

In index.js file:

import {StyledTabs, StyledTitle } from "./styled

In styled.js file:

export const StyledTabs = styled(Tabs)`
  display: inline-flex !important;
  margin-left: 15% !important;
`;

export const StyledTab = styled(Tab)`
  display: inline-flex !important;
  margin-left: 0% !important;
  padding: 0 !important;
`;


来源:https://stackoverflow.com/questions/50754680/splitting-styled-components-into-multiple-files-but-export-them-as-one-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!