最速でNext.jsのローカル環境を作成する

Next.js
2021-03-23

create-next-appとかよりもっとプレーンなNext.jsの環境をサクッと作りたい場合。

ディレクトリを作成して、、

mkdir next-app && cd next-app
# もしくは take next-app

以下のコマンドを実行

npm init -y
npm install next react react-dom
npm install typescript @types/react @types/node -D
mkdir src
mkdir src/pages
mkdir src/components
touch .env.local
{
  echo "import { NextPage } from 'next';"
  echo "const Index: NextPage<{}> = () => <div>Index</div>;"
  echo "export default Index;"
} > src/pages/index.tsx
npm set-script dev "next dev"
npm set-script build "next build"
npm set-script start "next start"

以上です。

あとは起動するだけ。起動時にtsconfigを自動で作成してくれます。

npm run dev

yarn版

yarn init -y
yarn add next react react-dom
yarn add typescript @types/react @types/node -D
mkdir src
mkdir src/pages
mkdir src/components
touch .env.local
{
  echo "import { NextPage } from 'next';"
  echo "const Index: NextPage<{}> = () => <div>Index</div>;"
  echo "export default Index;"
} > src/pages/index.tsx
npm set-script dev "next dev"
npm set-script build "next build"
npm set-script start "next start"
yarn dev

options

tailwindcss@2.1(jit版)を追加

https://github.com/vercel/next.js/tree/canary/examples/with-tailwindcss

※ 2021/04/25 時点のnext@10.1.3 の場合だと、postcssがコンフリクトする。その場合--legacy-peer-deps オプションを付け、古い依存関係を無視するようにする。

npm i autoprefixer postcss -D
npm i tailwindcss@2.1 -D
# tailwind.config.jsを生成
npx tailwindcss init
touch postcss.config.js

postcss.config.jsを追加

module.exports = {
  plugins: {
    tailwindcss: {},
    autoprefixer: {},
  },
}

tailwindのmodeを jit に変更 ( tailwind.config.js を追加 )

purgeに対象のJSXコンポーネントを指定する。

module.exports = {
  mode: 'jit',
  purge: ['./pages/**/*.{js,ts,jsx,tsx}', './components/**/*.{js,ts,jsx,tsx}'],
  ...
}

page/_app.tsx にtailwindcssをインポート

import 'tailwindcss/tailwind.css';
Written by Kyohei Tsukuda who lives and works in Tokyo 🇯🇵 , building useful things 🔧.