LoginSignup
13
11

More than 3 years have passed since last update.

Next v9 + TypeScript の環境構築

Last updated at Posted at 2019-10-03

NextJS + TypeScript 環境構築手順の備忘録です。バージョンはNext9.0.7

公式: Learn - TypeScript | Next.js

手順

プロジェクトディレクトリを作成してパッケージをインストールします。
パッケージ: react react-dom next typescript @types/react @types/react-dom @types/node

mkdir next-ts
cd next-ts
mkdir pages
touch pages/index.tsx
yarn add react react-dom next typescript @types/react @types/react-dom @types/node

package.jsonscripts を追加します。

package.json
...
"scripts": {
 "dev": "next",
 "build": "next build",
 "start": "next start"
}
...

動作確認

pages/index.tsxで動作を確認します。

pages/index.tsx
const IndexPage = () => <h1>Helloworld!</h1>;
export default IndexPage;
npm run dev

初回起動時にnext-env.d.tstsconfig.jsonが生成されます。
ts01.png

TypeScriptが効いているか確認します

タイプチェックをストリクトモードにしてみます。

tsconfig.json
...
"strict": true,
...
pages/index.tsx
const IndexPage = ({ userAgent }) => (
 <h1>Hello world! - useragent: {userAgent}</h1>
);

IndexPage.getInitialProps = async ({ req }) => {
  const userAgent = req ? req.headers['user-agent'] : navigator.userAgent;
  return { userAgent };
};

export default IndexPage;

VS CodeTypeScriptプラグインを入れている場合はエディタ側にエラー表示がでていると思います。

サーバーをnpm run devで再起動します。

ブラウザとターミナル両方にエラーがでます。
ts02.png

最後にタイプエラーを修正して終わりにします。

pages/index.tsx
import { NextPage } from 'next';

const IndexPage: NextPage<{ userAgent: string }> = ({ userAgent }) => (
  <h1>Hello world! - useragent: {userAgent}</h1>
);

IndexPage.getInitialProps = async ({ req }) => {
  const userAgent = req ? req.headers['user-agent'] || '' : navigator.userAgent;
  return { userAgent };
};
export default IndexPage;
13
11
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
13
11