我想从我自己的 .ts
文件中导出 styled-components/macro
但它不起作用。
自定义样式.ts
import styled from 'styled-components/macro'
import * as styledComponents from 'styled-components'
import { ThemeInterface } from './theme'
const {
css,
createGlobalStyle,
keyframes,
withTheme,
ThemeProvider,
} = styledComponents as styledComponents.ThemedStyledComponentsModule<ThemeInterface>
export { css, createGlobalStyle, keyframes, ThemeProvider, withTheme }
export default styled
App.tsx: 当我直接从 import styled from 'styled-components/macro' 导入它时,它提供了预期的调试功能。但是,当我从我的自己的文件 尝试时,出现了问题。预先谢谢你。
我尝试使用 export { css, createGlobalStyle, keyframes, ThemeProvider, withTheme, styled }
。但没有成功。
import React from 'react';
import styled from './custom-styled'
const StyledContainer = styled.div`
background: black;
`
const StyledSpan = styled.span`
color: white;
font-size: 20px;
`
function App() {
return (
<StyledContainer>
<StyledSpan>
Test
</StyledSpan>
</StyledContainer>
);
}
export default App;
最佳答案
如果您使用的是 typescript,则必须导入 @types/styled-components
:
npm i @types/styled-components
还需要babel-plugin-styled-components
:
npm install --save-dev babel-plugin-styled-components
并在根目录下创建一个.babelrc
配置文件。
.babelrc
{
"plugins": [
[
"babel-plugin-styled-components",
{
"ssr": true,
"minify": true,
"transpileTemplateLiterals": false,
"pure": false,
"displayName": false, // generate another classname
"fileName": false, // generate another classname
"preprocess": false
}
]
]
}
应用.tsx
import styled, {
Thing,
GlobalStyle,
StyledContainer,
StyledSpan
} from "./custom-styled";
import Reusable from "./Reusable";
const StyledContainer2 = styled(StyledContainer)``;
const StyledSpan2 = styled(StyledSpan)``;
const StyledSpan3 = styled(StyledSpan)`
color: orange;
font-weight: bold;
font-size: 1.5em;
`;
function App() {
return (
<StyledContainer2>
<GlobalStyle />
<Thing>Thing from suctom-styled</Thing>
<StyledSpan2>StyledSpan</StyledSpan2>
<StyledSpan3>Extend StyledSpan</StyledSpan3>
<Reusable />
</StyledContainer2>
);
}
export default App;
自定义样式.ts
import styled, {
css,
createGlobalStyle,
keyframes,
ThemeProvider
} from "styled-components/macro";
export const GlobalStyle = createGlobalStyle`
body {
overflow: hidden;
background-color: lightcoral;
}
`;
export const Thing = styled.div`
color: red;
`;
const move = keyframes`
50%{ transform: translateX(100px)}
`;
export const StyledContainer = styled.div`
display: flex;
flex-flow: column;
background: black;
`;
export const StyledSpan = styled.span`
color: white;
font-size: 20px;
animation: ${move} 2s linear infinite;
`;
export { css, createGlobalStyle, keyframes, ThemeProvider };
export default styled;
可重用.tsx
import { Thing, StyledContainer, StyledSpan } from "./custom-styled";
function Reusable() {
return (
<StyledContainer>
<Thing>Reusable Thing</Thing>
<StyledSpan>Reusable StyledSpan</StyledSpan>
</StyledContainer>
);
}
export default Reusable;
本地 DOM 检查器
本地 React DevTool
关于javascript - 从样式化组件宏重新导出样式化不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69547948/