styles폴더에 GlobalStyles.jsx 생성
import { createGlobalStyle } from 'styled-components';
import normalize from 'styled-normalize';
const GlobalStyle = createGlobalStyle`
${normalize}
/* 이하 스타일 정의 */
`;
나는 styled-components 와 styled-normalize를 같이 사용하려고한다.
근데 설치를 하려니 오류가떴다.
이유는 styled-components 버전 4, 5 에서만 styled-normalize를 지원했다.
따라서 이렇게 설치해줘야 에러없이 깔린다.
npm i styled-components@5
npm i styled-normalize
다깔면 GlobalStyles을 마저 짜준다.
import { createGlobalStyle } from 'styled-components';
import { normalize } from 'styled-normalize';
export const GlobalStyles = createGlobalStyle`
${normalize}
html,
body {
background-color: ${({ theme }) => theme.colors.backgroundColor};
color:${({ theme }) => theme.colors.textColor};
font-family: 'Noto Sans KR', sans-serif;
-webkit-user-select:none;
-moz-user-select:none;
-ms-user-select:none;
user-select:none;
}
button {
background: inherit;
border: none;
box-shadow: none;
border-radius: 0;
padding: 0;
cursor: pointer;
}
a,a:hover,a:active {
color: inherit;
text-decoration: none;
outline: none;
}
* {
box-sizing: border-box;
}
pre {
font-family: 'Noto Sans KR',sans-serif;
}
h1,h2,h3,h4,h5,h6,p{
margin:0;
}
ul,li{
padding:0;
margin:0;
list-style:none;
}
img {
width: 100%;
height: 100%;
object-fit: cover;
}
.blind{
position: absolute;
clip:rect(0 0 0 0);
width:0;
height:0;
overflow: hidden;
color:white;
}
`;
styles폴더에 theme.js 생성
theme.js엔 내가 원하는 기본 css 설정을 할수있다.
export const colors = {
primaryColor: '#ffc8c8',
subColor: '#ef9595',
textColor: '#867070',
backgroundColor: '#f8f5f8',
gray: {
100: '#f1f1f0',
200: '#d9d9d6',
300: '#c8c9c7',
400: '#b1b3b3',
500: '#97999b',
600: '#75787b',
700: '#54565a',
800: '#212721',
},
white: '#ffffff',
black: '#000000',
};
export const flex = {
center: `
display:flex;
justify-contents:center;
align-items:center;
`,
centerColumn: `
display:flex;
flex-direction:column;
justify-contents:center;
align-items:center;
`,
};
const deviceSizes = {
xs: '575px',
sm: '576px',
md: '768px',
lg: '992px',
xl: '1200px',
xxl: '1600px',
};
export const devices = {
xs: `screen and (min-width: ${deviceSizes.xs})`,
sm: `screen and (min-width: ${deviceSizes.sm})`,
md: `screen and (min-width: ${deviceSizes.md})`,
lg: `screen and (min-width: ${deviceSizes.lg})`,
xl: `screen and (min-width: ${deviceSizes.xl})`,
xxl: `screen and (min-width: ${deviceSizes.xxl})`,
};
export const theme = {
colors,
flex,
devices,
};
export default theme;
_app.js에 다음과같이 입력한다.
import { GlobalStyles } from '@styles/GlobalStyles';
import theme from '@styles/theme';
import { ThemeProvider } from 'styled-components';
function MyApp({ Component, pageProps }) {
return (
<ThemeProvider theme={theme}>
<GlobalStyles />
<Component {...pageProps} />
</ThemeProvider>
);
}
export default MyApp;
그러고 local:3000에 접속해보면 에러가뜬다.
이때는 _document.js 와 styled-components가 적용되도록 babel-plugin을 설치해줘야함
pages에 _document.js를 생성한다.
// app.js가 document로 감싸지면서 head,body등을 수정할수있음
import React from 'react';
import Document, { Head, Html, Main, NextScript } from 'next/document';
import { ServerStyleSheet } from 'styled-components';
export default class MyDocument extends Document {
static async getInitialProps(ctx) {
const sheet = new ServerStyleSheet(); // styled-components를 서버사이드렌더링할수있게 불러온다.
const originalRenderPage = ctx.renderPage;
try {
// stylesheet가 styled-components를 서버사이드 렌더링할수있게 해주는 기능
ctx.renderPage = () =>
originalRenderPage({
enhanceApp: (App) => (props) =>
sheet.collectStyles(<App {...props} />),
});
const initialProps = await Document.getInitialProps(ctx);
return {
...initialProps,
styles: (
<>
{initialProps.styles}
{sheet.getStyleElement()}
</>
),
};
} catch (err) {
console.error(err);
} finally {
sheet.seal();
}
}
render() {
return (
<Html>
<Head />
<body>
<Main />
{/* https://polyfill.io/v3/url-builder // nextscript나 Main위에 써줘야함*/}
{/* 최신문법은 babel로 되는데, map set propmise등은 babel로안되서 Polyfill.io를 써주면 ie에서도 돌아감 */}
<script src="https://polyfill.io/v3/polyfill.min.js?features=default%2Ces2015%2Ces2016%2Ces2017%2Ces2018%2Ces2019" />
<NextScript />
</body>
</Html>
);
}
}
npm i babel-plugin-styled-components
루트에 .babelrc 파일생성
// 스타일드컴포넌트를 서버사이드렌드링 하기 위함. npm i babel-plugin-styled-components
{
"presets": ["next/babel"],
"plugins": [
[
"babel-plugin-styled-components",
{
"ssr": true,
"displayName": true // 개발자도구에서 컴포넌트이름이 외계어가아닌 직관적으로 보임
}
]
]
}
이제 서버를 다시 npm run dev 해보면 콘솔에 오류가 안뜨는걸 확인할수있다.