5
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【2021年最新版】React+TypeScript+Prettier+Material-ui+Tailwindcssの環境構築をコピペだけで行う

Last updated at Posted at 2021-07-20

皆さんこんにちは!

梅雨が明け、暑さは最高潮ですね。

僕は夏のじめじめがとても嫌いで、冬の方が断然好きですね。

前置きはさておき

今回はReactの環境構築のテンプレートをご紹介するので、ぜひReactで開発を行うことが多いという方やこれからReactの環境構築を行いたい、またReactの環境構築を忘れたという方々すべてにコピペだけで環境構築を行えますので、ぜひストックして頂けると幸いです。

特に詳しい説明などはしませんのでご了承ください。

それでは、コピペだけで環境構築を行っていきましょう!

プロジェクトの作成(TypeScript付き)

npx create-react-app [プロジェクト名] --template typescript

Prettier導入

npm i -D prettier
package.json
{
  // 省略
  "prettier": {
    "printWidth": 120,
    "semi": true,
    "singleQuote": false,
    "tabWidth": 4,
    "trailingComma": "all"
  }
}
package.json
{
  "scripts": {
    // 省略
    "prettier": "prettier --write ./src/**/*.{js,ts,tsx}",
  },
}

Material-ui導入

npm i @material-ui/core @material-ui/icons @material-ui/styles @material-ui/lab

Tailwindcss導入

npm install -D tailwindcss@npm:@tailwindcss/postcss7-compat postcss@^7 autoprefixer@^9
npm install @craco/craco
package.json
    "scripts": {
      "start": "TAILWIND_MODE=watch craco start",
      "build": "craco build",
      "test": "craco test",
    }
touch craco.config.js
craco.config.js
module.exports = {
    style: {
        postcss: {
            plugins: [
                require('tailwindcss'),
                require('autoprefixer'),
            ],
        },
    },
}
npx tailwindcss init -p
tailwind.config.js
  module.exports = {
   mode: "jit", // 追加
   // purge: [],
   purge: ['./src/**/*.{js,jsx,ts,tsx}', './public/index.html'],
    darkMode: false, // or 'media' or 'class'
    theme: {
      extend: {},
    },
    variants: {
      extend: {},
    },
    plugins: [],
  }
src/index.css
@tailwind base;
@tailwind components;
@tailwind utilities;

/* Tailwindcssを導入すると、hタグのフォントサイズが変わるのを防ぐ */
h1 {
    font-size: 48px;
    line-height: 1;
}
h2 {
    font-size: 36px;
    line-height: 1.333;
}
h3 {
    font-size: 24px;
    line-height: 1;
}
h4, h5, h6 {
    font-size: 16px;
    line-height: 1.5;
}

これだけでReactの環境構築は完了です!

下の番外編ではRouterの設定やMaterial-uiのテーマ設定などを行います。

興味のある方、導入したい方は引き続きご覧ください。

番外編

Routerの設置

npm i @types/react-router-dom
touch ./src/history.js ./src/ScrollToTop.tsx ./src/Routing.tsx
src/history.js
import { createHashHistory } from "history";
// OR
import { createBrowserHistory } from "history";

export default createBrowserHistory();
// OR
export default createHashHistory();

createBrowserHistorycreateHashHistoryはお好きな方をお選びください。

特に理由が無い方は、createBrowserHistoryを選ぶと良いでしょう。

ページ遷移の際にスクロール位置がトップに行くように設定

src/ScrollToTop.tsx
import { withRouter } from "react-router-dom";
import { useEffect } from "react";
import * as H from "history";

type Props = {
  history: H.History;
};

const ScrollToTop: React.FC<Props> = ({ history }) => {
  useEffect(() => {
    const unlisten = history.listen(() => {
      window.scrollTo(0, 0);
    });
    return () => {
      unlisten();
    };
  }, [history]);

  return null;
};

export default withRouter(ScrollToTop);
src/Routing.tsx
import { Router, Route, Switch } from "react-router-dom";
import history from "./history";
import ScrollToTop from "./ScrollToTop";

const Routing: React.FC = () => {
    return (
        <Router history={history}>
          <ScrollToTop />
          <Switch>
            <Route exact path="/" component={Home} />
          </Switch>
        </Router>
    );
};

export default Routing;
src/App.tsx
import Routing from "./Routing";

const App: React.FC = () => {
  return (
    <div>
       <Routing />
    </div>
  );
};

export default App;

Material-uiのテーマ設定

touch ./src/Theme.ts
src/Theme.ts
import { createMuiTheme } from "@material-ui/core/styles";

export const Theme = createMuiTheme({
  palette: {
    primary: {
      main: "#2196f3",
    },
    secondary: {
      main: "#009688",
    },
  },
});
src/App.tsx
import { ThemeProvider } from "@material-ui/core";
import Routing from "./Routing";
import { Theme } from "./Theme";

const App: React.FC = () => {
  return (
    <div>
      <ThemeProvider theme={Theme}>
        <Routing />
      </ThemeProvider>
    </div>
  );
};

export default App;

環境変数

touch .env
/.env
# development
REACT_APP_HOST = "localhost"

# production
REACT_APP_HOST = "www.example.com"
example.js
console.log(process.env.REACT_APP_HOST)

ビルド時の注意点

本番環境の構築を行う際に、ページがが真っ白になる場合があります。

その理由は2つあり、ビルドしたファイルが他のファイルを読み取る際に絶対パスになっている、もしくはヒストリー(history)の設定に不備がある。

なので、以下のどちらかの方法を試してみてください。

package.json
{
  "homepage": "./",
}
src/history.js
import { createHashHistory } from "history";

export default createHashHistory();

このようにしてReactの環境構築をコピペだけで行うことができます。

結構説明を端折ったので、もし説明して欲しい部分があればコメントで質問してください。

以上、「【2021年最新版】React+TypeScript+Prettier+Material-ui+Tailwindcssの環境構築をコピペだけで行う」でした!

Thank you for reading

5
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?