0
0

More than 1 year has passed since last update.

Next.jsでTypeScript&Tailwind.cssを導入する環境構築手順

Last updated at Posted at 2022-07-05

はじめに

基本的に自分用のメモですが、Next.jsで開発するときにTypeScriptとTailwind.cssを導入する方は参考にしてください

Next.jsの導入

node.jsはインストールされている前提とします

VSコード上のターミナル上で以下のコマンドを実行

npx create-next-app [プロジェクト名]

こちらはyarnで実行されるので、yarnをインストールしていない人はインストールしましょう
もしくは、npmでも実行できるので、yarnを使わない場合は--use-npmをオプション引数につけて実行してください
なお、[プロジェクト名]を.にすると現時点のフォルダに直接プロジェクトが作成されます

また、PowerShellのセキュリティに弾かれるエラーが出た場合は以下のコマンドを実行の後再度実行してください

Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope Process

Babelと静的コード解析ツールの導入

1 Project folder 直下に".babelrc"ファイルを作成して下記設定を追加
.babelrc

{
   "presets": ["next/babel"]
}

2 prettierの設定

.prettierrcを作成する

{
    "singleQuote": true,
    "semi": false
}

またVSコードのsettingsで
Require Config
Format On Save
にチェックを入れてセーブ時にフォーマットされるようにします

TypeScript導入

TSの導入方法は以下を参考に行います
https://nextjs.org/learn/excel/typescript/create-tsconfig

1
tsconfig.jsonの空ファイルを作成する

2

yarn add --dev typescript @types/react @types/node

3 開発server起動

yarn dev

これを行うことで設定ファイルが自動生成されたり、先ほど空ファイルの中身が自動追記されたりする

4 _app.js, index.js の拡張子を tsx に変更

5 AppProps型追記

import { AppProps } from 'next/app'

function MyApp({ Component, pageProps }: AppProps) {
    return <Component {...pageProps} />
}

export default MyApp

6 ライブラリのインポートで警告が出る場合

以下で警告が消える可能性があるので試す
tsconfig.json

"compilerOptions": {
    "moduleResolution":"node",
},

Tailwindの導入

CSSはTailwindを使用しようと思うので、公式ドキュメントの手順を参考に導入を行う
https://tailwindcss.com/docs/guides/nextjs

CSS自体はチートシートを参照して開発を進める
https://nerdcave.com/tailwind-cheat-sheet

1 必要moduleのインストール&tailwind.config.js, postcss.config.jsの生成

npm install -D tailwindcss postcss autoprefixer
npx tailwindcss init -p

yarnを使っていればyarn addでもいい

2 tailwind.config.jsのpurge設定追加

module.exports = {
  content: [
    "./pages/**/*.{js,ts,jsx,tsx}", // add
    "./components/**/*.{js,ts,jsx,tsx}", // add
  ],
}
  1. componentsフォルダの作成
    プロジェクト直下

  2. globals.cssの編集
    中身を以下の3行に完全に置き換える

@tailwind base;
@tailwind components;
@tailwind utilities;

5 プロジェクト時に自動生成されている不要なStyle情報を削除する

プロジェクト作成時に
styles/Home.module.cssが生成されているが、使わない場合は削除する

これで設定は完了です

0
0
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
0
0