next js에 css 적용 (bootstrap, styled-component)

2019. 8. 22. 14:30·WEB/Nextjs

next js 프레임 워크는 서버사이드와 클라이언트 사이드 렌더링이 이루어져 기존의 react에서 처럼 css를 import하는 방법으로는 css를 적용 시킬 수 없다. 그에 따라 styled-component와 bootstrap을 적용 시키기 위해 여러 삽질(?)을 했고 적용이 완료 되어 정리하려고 한다.


styled-component 적용

nextjs에서 제공하는 보일러 플레이트
https://github.com/zeit/next.js/tree/master/examples/with-styled-components


우선 styled-component를 적용 시키기 위해서는 babel 설정과 _document.js 설정을 해주어야 한다.

node-module 설치


npm install styled-components


npm install babel-plugin-styled-components



루트폴더에 .babelrc 파일 생성


{
"presets": ["next/babel"],
"plugins": [
[
"styled-components",
{
"ssr": true,
"displayName": true,
"preprocess": false
}
]
]
}


/pages/_document.js


import Document, { Head, Main, NextScript } from 'next/document';
// Import styled components ServerStyleSheet
import { ServerStyleSheet } from 'styled-components';

export default class MyDocument extends Document {
static getInitialProps({ renderPage }) {
// Step 1: Create an instance of ServerStyleSheet
const sheet = new ServerStyleSheet();

// Step 2: Retrieve styles from components in the page
const page = renderPage(App => props => sheet.collectStyles(<App {...props} />));

// Step 3: Extract the styles as <style> tags
const styleTags = sheet.getStyleElement();

// Step 4: Pass styleTags as a prop
return { ...page, styleTags };
}

render() {
return (
<html>
<Head>
{/* Step 5: Output the styles in the head */}
<meta charSet='utf-8' />
<meta name='viewport' content='initial-scale=1.0, width=device-width' />
{this.props.styleTags}
</Head>
<body>
<Main />
<NextScript />
</body>
</html>
);
}
}

설정이 끝나면 react에서 사용 하듯이 컴포넌트에 styled-component를 import시켜서 사용할 수 있다.

* 설정 후에는 서버를 꼈다가 다시 켜야 적용된다. 재시작 하지 않으면 오류를 내뱉음

참고 : https://dev.to/aprietof/nextjs--styled-components-the-really-simple-guide----101c

bootstrap 등 css 라이브러리 적용하기

이런 저런 삽질을 많이 했지만 간단한 방법으로 해결되었다. 이전부터 많은 질문들이 있었지만, 지금은 next에서 자체적으로 plugin을 지원한다.

node_modules 설치
npm install @zeit/next-css

루트 폴더에 next.config.js 파일을 생성한 후 아래의 내용을 넣는다

// next.config.js
const withCSS = require('@zeit/next-css');
module.exports = withCSS({});

css module로 사용하지 않고 css 파일을 import하여 className을 이용하여 css를 적용 시키는 방법에 대한 설정이다. 
자세한 내용이 궁금하다면 아래의 첫번째 참고 url에서 확인하자.

설정 후엔 아래와 같은 방식으로 css 파일을 import하여 사용할 수 있다.
import 'bootstrap/dist/css/bootstrap.css';

매번 컴포넌트마다 넣기에는 귀찮으니 _app.js를 커스텀해서 한 줄만 넣어 모든 컴포넌트에 적용되도록 하자
pages/_app.js 파일을 생성한 후 아래와 같이 넣으면 설정이 끝난다. 이 또한 자세한 내용은 아래의 두번째 참고url을 확인하자
import React from 'react';
import App from 'next/app';

import 'bootstrap/dist/css/bootstrap.css';

class MyApp extends App {
// Only uncomment this method if you have blocking data requirements for
// every single page in your application. This disables the ability to
// perform automatic static optimization, causing every page in your app to
// be server-side rendered.
//
// static async getInitialProps(appContext) {
// // calls page's `getInitialProps` and fills `appProps.pageProps`
// const appProps = await App.getInitialProps(appContext);
//
// return { ...appProps }
// }

render() {
const { Component, pageProps } = this.props;
return <Component {...pageProps} />;
}
}

export default MyApp;


참고 : https://github.com/zeit/next-plugins/tree/master/packages/next-css 

참고 : https://nextjs.org/docs#custom-app




저작자표시 (새창열림)

'WEB > Nextjs' 카테고리의 다른 글

Next js 튜토리얼 1편: 시작하기  (0) 2019.09.30
react get browser size  (0) 2019.09.10
next js scroll  (0) 2019.09.06
head 설정  (0) 2019.08.20
next js 배포  (0) 2019.08.20
'WEB/Nextjs' 카테고리의 다른 글
  • react get browser size
  • next js scroll
  • head 설정
  • next js 배포
vitnal
vitnal
4년차 프론트엔드 개발자입니다. react를 사용하여 웹 서비스를 개발한 경험이 있습니다. github: https://github.com/jch1223
  • vitnal
    vitnal 아카이브
    vitnal
  • 전체
    오늘
    어제
    • 분류 전체보기 (146)
      • AI (1)
      • WEB (76)
        • React (21)
        • Nextjs (17)
        • JavaScript (16)
        • React Native (5)
        • HTML & CSS (7)
      • CS (3)
      • Git (15)
      • Dev Tools (23)
      • Deploy (12)
      • Tech Memo (8)
      • Retrospect (7)
  • 반응형
  • hELLO· Designed By정상우.v4.10.5
vitnal
next js에 css 적용 (bootstrap, styled-component)
상단으로

티스토리툴바