LoginSignup
0
0

More than 1 year has passed since last update.

Next.js の使い方

Last updated at Posted at 2022-05-12

こちらの React のプログラムを Next.js に変換します。
React の使い方 (その3)
こちらのページを参考にしました。
Getting Started with Next.js

フォルダーに package.json だけを用意します。

$ tree
.
└── package.json
package.json
{}

モジュールのインストール

npm install react react-dom next

フォルダーは次のようになります。

$ tree -L 2
.
├── node_modules
│   ├── @next
│   ├── caniuse-lite
│   ├── js-tokens
│   ├── loose-envify
│   ├── nanoid
│   ├── next
│   ├── picocolors
│   ├── postcss
│   ├── react
│   ├── react-dom
│   ├── scheduler
│   ├── source-map-js
│   └── styled-jsx
├── package-lock.json
└── package.json
package.json
{
  "dependencies": {
    "next": "^12.2.0",
    "react": "^18.2.0",
    "react-dom": "^18.2.0"
  }
}

プログラムと実行環境の用意

pages というフォルダーを作成

mkdir pages

次を作成します。

pages/index.js


import { useState } from 'react';
function Header({ title }) {
  return <h1>{title ? title : 'Default title'}</h1>;
}

export default function HomePage() {
  const names = ['夏目漱石', '島崎藤村', '森鴎外','芥川龍之介','太宰治']

  const [likes, setLikes] = useState(0);

  function handleClick() {
    setLikes(likes + 1);
  }

  return (
    <div>
      <Header title="こんにちは" />
      <ul>
        {names.map((name) => (
          <li key={name}>{name}</li>
        ))}
      </ul>

      <button onClick={handleClick}>Like ({likes})</button>
    </div>
  );
}

package.json の改造

package.json
{
"scripts": {
        "dev": "next dev",
	"build": "next build",
	"start": "next start",
	"export": "next export"
    },
  "dependencies": {
    "next": "^12.2.0",
    "react": "^18.2.0",
    "react-dom": "^18.2.0"
  }
}

サーバーの起動 ##

npm run dev

ブラウザーでアクセス

http://localhost:3000
nextjs_may1201.png

次のバージョンで確認しました。

$ node --version 
v18.4.0
$ npm --version
8.10.0

Production Build

npm run build

サーバーの実行

npm run start

Vercel 以外にデプロイ

npm run build
npm run export

サーバーの実行 (4種類のサーバーを使ってみます。)

serve -s out
cd out
http-server
cd out
python -m http.server
php -S 0.0.0.0:8000 -t out
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