
스토리북으로 컴포넌트를 관리하다보면 실제 리액트 프로젝트의 index.html의 헤더, 전역으로 설정한 css, 경로별칭, 라우팅 등의 설정이 적용되지 않아 기대하던 디자인과 동작이 다른경우가 있다.
예를들어 리액트 프로젝트의 index.html에서 reset css , 폰트 , 전역 css 등과 같은 설정을 해두었지만 스토리북에서는 이렇게 설정한 리액트 프로젝트의 index.html이 아닌 스토리북 자체의 index.html을 사용하기 때문에 적용이 되어있지 않다.
따라서 리액트 프로젝트에 설정했던 것처럼 스토리북에서도 추가로 설정을 해주어야한다.
stories 파일 내부에서 import 경로의 별칭을 줄 수 있다. .storybook 폴더 하위에 main.js 이름의 파일을 생성하여 아래와 같이 별칭을 주면 된다.
// .storybook/main.js
// 파일 경로가 ..으로 시작하는 이유는 최상위 route에 위치하고 있다.
// 해당 폴더를 기준해서 탐색하기 때문이다.
const path = require('path');
webpackFinal: async (config) => {
config.resolve.alias['@components'] = path.resolve(
__dirname,
'../src/components',
);
config.resolve.alias['@hooks'] = path.resolve(__dirname, '../src/hooks');
config.resolve.alias['@contexts'] = path.resolve(
__dirname,
'../src/contexts',
);
config.resolve.alias['@pages'] = path.resolve(__dirname, '../src/pages');
config.resolve.alias['@styles'] = path.resolve(__dirname, '../src/styles');
config.resolve.alias['@validators'] = path.resolve(
__dirname,
'../src/validators',
);
config.resolve.alias['@apis'] = path.resolve(__dirname, '../src/apis');
config.resolve.alias['@utils'] = path.resolve(__dirname, '../src/utils');
return config;
}
스토리북 index.html의 헤더를 설정하기 위해서는 .storybook 폴더 하위에 preview-head.html 이름의 파일을 생성하여 아래와 같이 적용하고 싶은 헤더를 작성해주면 된다.
<!-- .storybook/preview-head.html -->
<link
rel="stylesheet"
href="https://fonts.googleapis.com/icon?family=Material+Icons"
/>
<link
href="https://fonts.googleapis.com/css2?family=Noto+Sans+KR:wght@400;500;700&display=swap"
rel="stylesheet"
/>
<link
rel="stylesheet"
href="https://cdn.jsdelivr.net/npm/reset-css@5.0.1/reset.min.css"
/>
스토리북 자체에 전역 css를 설정하기 위해서는 .storybook 폴더 하위에 "적용하고 싶은 css파일"을 생성하고 preview.js 파일에서 아래와 같이 import 해주면 된다.
import './index.css'; // *적용하고 싶은 css파일을 import
// 기존에 작성되어있는 내용
export const parameters = {
actions: { argTypesRegex: '^on[A-Z].*' },
controls: {
matchers: {
color: /(background|color)$/i,
date: /Date$/,
},
},
};
참고
컴포넌트에 react-router react-router-dom 을 사용하여 <Link>를 걸어둔 컴포넌트에서 스토리북에서는 어디로 라우팅할지 설정을 해줄 수 있다.
.storybook 폴더 하위에 previw.js 파일에서 아래와 같이 작성하면 모든 컴포넌트에 적용이 된다.
import React from "react";
import { addDecorator } from "@storybook/react";
import { MemoryRouter } from "react-router"; // or "react-router-dom";
addDecorator(story => <MemoryRouter initialEntries={['/']}>{story()}</MemoryRouter>);
각각의 컴포넌트 스토리파일에 아래와 같이 MemoryRouter 를 import 하여 어디로 라우팅될지 설정할 수 있다
import React from 'react';
import { MemoryRouter } from 'react-router-dom'; // or "react-router"
import { Button } from '@components'
export default {
title : 'Components/Button',
//Wrapping the story inside the router
decorators : [(Story) => (<MemoryRouter><Story/></MemoryRouter>)],
};
이밖에 첨부한 참고링크를 보면 다양한 방식으로 설정할 수 있다.