1.はじめに
TypeScriptでReactを書く際の初期設定について記録しました。ファイル作成からstorybookを用いた開発についてまで触れています。初めてなのでおかしい部分が多々あるかもしれません
2.環境構築
適当なディレクトリに入る
git管理するディレクトリ達はひとつのフォルダにまとめるようにしているのでターミナルでそちらに移動します。
cd ~/gitspace
Reactのプロジェクトの作成
Reactアプリを作るためのテンプレートがあるのでその雛形を利用します。
npx create-react-app <プロジェクト名> --template typescript
作成したプロジェクトに移動します
cd <プロジェクト名>
happy hacking!
と出ればインストール成功です(結構時間がかかった)。
yarn start
でlocalhost3000サーバーを起動してこのような画面が出てくるはずです。
code .
でVScodeを起動します。
リポジトリを作成して反映する
GitHubでリポジトリを作成して、そこに作成したものをpushします。
git remote add origin <リポジトリのURL>
3.不要なファイルの除去
次のファイルは不要なので除去しておきます。
- App.css
- App.test.tsx
- logo.svg
4.App.tsxの書き換え
import React from 'react';
const App: React.FC = () => {
return(
<h1>Hello React!</h1>
);
};
export default App;
5.componentファイルの作成
atomic designだと細かすぎるのでuiParts(atoms,molecules相当)、projects(organisms,templates相当)、pagesに分けてパーツを作成していきます。
最初にファイルを作るとエラーが起こりますが、これはtsconfig.json
でisolateModules
がtrueになっているからだと思われます(デフォルトでfalse)。importもexportもしていないファイルをコンパイルエラーとするようなので一旦export {}
を書いておいて解決しました。
--src
|
--components
|
|--uiParts
| |
| --example
| |--index.tsx
| |--style.tsx
| |--index.stories.tsx
|--projects
|--pages
import { StyledText } from "./style";
type ExampleTextProps = {
text: string;
}
export const ExampleText = ({ text }: ExampleTextProps) => {
return (
<StyledText>{text}</StyledText>
);
}
import styled from "styled-components";
export const StyledText = styled.p`
color: #0A6ABF;
`;
import { ComponentStory } from "@storybook/react";
import { ExampleText } from "./index";
export default {
title: "uiParts/ExampleText",
component: ExampleText,
};
const Template: ComponentStory<typeof ExampleText> = (args) => (
<ExampleText {...args} />
);
export const Basic = Template.bind({});
Basic.args = {
text: "テキスト",
};
styled-componentsを使えるようにする
初期状態ではstyled-componentsが存在しないようでエラー吐かれるのでインストールします。
npm install --save styled-components
package.json
に追加されます。
storybookを使えるようにする
初期状態ではstorybookを使えない(エラーで怒られる)ので、storybookをインストールします(時間かかった)。
npx storybook init
yarn storybook
でstorybookを起動できます。