🦋

【Next.js】個人的Next.js(Pages Router)の始め方

に公開

インストール

.で現在のディレクトリにインストール

npx create-next-app@latest .

選択

Would you like to use TypeScript? Yes
Would you like to use ESLint? Yes
Would you like to use Tailwind CSS? No
Would you like to use `src/` directory? Yes
Would you like to use App Router? (recommended) No
Would you like to customize the default import alias (@/*)? No

Sassのインストール

npm install --save-dev sass

configの設定

next.config.mjs
/** @type {import('next').NextConfig} */
const nextConfig = {
  reactStrictMode: true,
  trailingSlash: true,
};

export default nextConfig;
  • ビルドしてHTMLを出力する場合は下記を追加
  • Next.jsの画像最適化機能はOFFにする必要あり

参考:https://nextjs.org/docs/app/building-your-application/deploying/static-exports

next.config.mjs
/** @type {import('next').NextConfig} */
const nextConfig = {
  ...
  output: 'export',
  images: {
    unoptimized: true,
  },
};

サブディレクトリにデプロイする場合はbasePathassetPrefixを追記

basePath
目的: アプリケーション全体のベースURLを設定します。
影響: すべてのページ、APIルート、静的ファイルのパスに影響します。

assetPrefix
目的: 静的アセット(画像、JavaScript、CSSなど)のURLのプレフィックスを設定します。
影響: 静的アセットの読み込み元に影響します。CDNなどの外部サーバーからアセットを提供する場合に使用します。

next.config.mjs
const isProd = process.env.NODE_ENV === 'production'
const prefixPath = isProd ? '/docs' : ''

/** @type {import('next').NextConfig} */
const nextConfig = {
  reactStrictMode: true,
  trailingSlash: true,
  output: 'export',
  images: {
    unoptimized: true,
  },
  basePath: prefixPath,
  assetPrefix: prefixPath,
};

export default nextConfig;

JSX・CSS ModuleでBEMみたいに書く時

  • modifierの--.で繋ぐ方法では記述できないので、配列の[]を用いる(__は使用可能)
  • []の中でさらにテンプレートリテラルを使用可能
interface Props {
  data: string;
  onClick: (e: React.MouseEvent<HTMLButtonElement>) => void;
  text: string;
}

export default function AreaBtn({ data, onClick, text }: Props) {
  return (
    <button className={ `${styles.areaBtn} ${styles[`areaBtn--${data}`]} `} type="button" data-area={data} onClick={onClick}>
      {text}
    </button>
  )
}

prismaを活用する

sqliteを使用

datasource db {
  provider = "sqlite"
  url      = env("DATABASE_URL")
}

generator client {
  provider = "prisma-client-js"
}

model User {
  id       Int      @id @default(autoincrement())
  email    String   @unique
  password String
  createdAt DateTime @default(now())
}

.env にデータベースのパスを設定

DATABASE_URL="file:./dev.db"

下記を実行
./dev.db ファイルがプロジェクトルートに自動生成される
Prisma が定義したモデルに基づいてデータベース構造をセットアップ

npx prisma migrate dev --name init

データベースを確認

npx prisma studio

Discussion