Closed10
Next.js+TypeScriptでWeb制作テンプレートを作成してみる🌞

Node.jsのバージョン設定
2022年9月19日時点でNode.jsの安定バージョンは16.17.0
今回はnodenv経由で上記バージョンをインストールする。
※nodenv本体のインストール方法は下記が参考になりました。
- Node.jsの最新バージョンをインストールできるように、nodenvを更新する
brew upgrade node-build
- Node.jsのバージョン
16.17.0
をインストール
nodenv install 16.17.0
- プロジェクトのルートディレクトリで.node-versionを作成し、バージョンを指定する
nodenv local 16.17.0
- 上記バージョンでYarnが利用できるようにインストール
npm install -g yarn

getLayoutの活用/Atomic Designを採用したコンポーネント設計
下記を参考にNext.jsのgetLayoutを活用する。
ディレクトリ構成・コンポーネント設計(Atomic Design)は下記を参考に構成してみる。
愛すべきTakepepeさん。

Tailwind CSSの導入
汎用的に利用できるCSSのclassを作る手間を減らすことを目的にTailwind CSSを導入する。
CSS設計のFLOCSSに馴染みがあったのと、purge機能が搭載しているのも採用理由の1つ。
- Tailwind CSSと関連パッケージのインストール
yarn add -D tailwindcss postcss autoprefixer
- Tailwind CSS関連の設定ファイルの作成
npx tailwindcss init -p
- 設定の追加(purgeを有効化)
tailwind.config.js
/** @type {import('tailwindcss').Config} */
module.exports = {
content: ["./src/pages/**/*.{js,ts,jsx,tsx}", "./src/components/**/*.{js,ts,jsx,tsx}"], // 今回修正分
theme: {
extend: {},
},
plugins: [],
};
- global.cssにTailwind CSSを読み込ませる
src/styles/globals.css
@import "tailwindcss/base";
@import "tailwindcss/components";
@import "tailwindcss/utilities";
- Tailwind CSSをStorybookで読み込む
yarn add -D @storybook/addon-postcss
.storybook/main.js
const path = require("path");
const rootPath = path.resolve(__dirname, "../src/");
module.exports = {
stories: ["../src/**/*.stories.mdx", "../src/**/*.stories.@(js|jsx|ts|tsx)"],
addons: [
"@storybook/addon-links",
"@storybook/addon-essentials",
"@storybook/addon-interactions",
"@storybook/preset-scss",
"storybook-addon-next-router",
+ {
+ name: "@storybook/addon-postcss",
+ options: {
+ postcssLoaderOptions: {
+ implementation: require("postcss"),
+ },
+ },
+ },
],
framework: "@storybook/react",
core: {
builder: "@storybook/builder-webpack5",
},
staticDirs: ["../public"],
webpackFinal: async (config, { configType }) => {
config.resolve.alias["@"] = rootPath;
return config;
},
};

next export(静的HTMLの生成)ができるようにする
静的HTMLの生成(export)を実現するため、以下を参考にpackage.json
を修正する。

Tailwind Config Viewerの導入
Tailwind CSSで用意されたclassを見える化できるTailwind Config Viewerをインストールする。
yarn add -D tailwind-config-viewer
package.json
{
"scripts": {
"dev": "next dev",
"build": "next build && next export",
"start": "next start",
"lint": "next lint",
"storybook": "start-storybook -p 6006",
"build-storybook": "build-storybook",
+ "tailwind-config-viewer": "tailwind-config-viewer -o"
},
}

TailWind CSSの設定をカスタマイズする
- 1pxごとのmarginやpadding、font-sizeのclassを生成できるようにする。
tailwind.config.js
/** @type {import('tailwindcss').Config} */
+ const object = (limit, base = 16) => {
+ return {
+ ...[...Array(limit + 1)].reduce((object, _, index) => {
+ object[`${index}`] = `${index / base}rem`;
+ return object;
+ }, {}),
+ };
+ };
module.exports = {
content: ["./src/pages/**/*.{js,ts,jsx,tsx}", "./src/components/**/*.{js,ts,jsx,tsx}"],
theme: {
extend: {},
+ spacing: object(200),
+ fontSize: object(80),
},
plugins: [],
};
- ブレイクポイントをカスタマイズする
tailwind.config.js
// 上記略
module.exports = {
content: ["./src/pages/**/*.{js,ts,jsx,tsx}", "./src/components/**/*.{js,ts,jsx,tsx}"],
theme: {
extend: {
+ screens: {
+ pc: { raw: "all and (max-width: 1365px)" },
+ tb: { raw: "only screen and (max-width: 1023px)" },
+ sp: { raw: "only screen and (max-width: 767px)" },
+ print: { raw: "print" },
+ },
},
// 中略
},
plugins: [],
};
- HTMLタグに付与したTailwindCSSのclassの順番をファイル保存時に自動で並び替えてくれるようにする
yarn add -D prettier-plugin-tailwindcss
公式でも推奨されていました。

hygen(コードジェネレーター)の導入
yarn add -D hygen
package.json
{
// 上記略
"scripts": {
"dev": "next dev",
"build": "next build && next export",
"start": "next start",
"lint": "next lint",
"storybook": "start-storybook -p 6006",
"build-storybook": "build-storybook",
"tailwind-config-viewer": "tailwind-config-viewer -o",
+ "hygen:component": "hygen component new"
},
// 下記略
component/new/prompt.js
const inputValidator = (input) => {
if (input !== "") {
return true;
}
};
module.exports = [
{
type: "input",
name: "name",
message: "コンポーネントの名前を指定してください。ex) Button",
validate: inputValidator,
},
{
type: "input",
name: "path",
message: "src/components以下のパスを指定してください。ex) atoms",
validate: inputValidator,
},
{
type: "toggle",
name: "withCssModule",
message: ".module.scssも一緒に作成しますか?",
disabled: "いいえ",
enabled: "はい",
initial: true,
},
{
type: "toggle",
name: "withStory",
message: ".stories.tsxも一緒に作成しますか?",
disabled: "いいえ",
enabled: "はい",
initial: true,
},
];
component/new/index.tsx.ejs.t
---
to: src/components/<%= path %>/<%= name %>/index.tsx
---
export { <%= name %> } from "@/components/<%= path %>/<%= name %>/<%= name %>";
component/new/component.tsx.ejs.t
---
to: src/components/<%= path %>/<%= name %>/<%= name %>.tsx
---
import styles from "@/components/<%= path %>/<%= name %>/<%= name %>.module.scss";
type <%= name %>Props = {
data: string
}
export const <%= name %> = ({ data }: <%= name %>Props) => {
return <div className={styles.<%= h.changeCase.camelCase(name) %>}>{data}</div>
}
component/new/module.scss.ejs.t
---
to: "<%= withCssModule ? `src/components/${path}/${name}/${name}.module.scss` : null %>"
---
.<%= h.changeCase.camelCase(name); %> {
}
component/new/stories.tsx.ejs.t
---
to: "<%= withStory ? `src/components/${path}/${name}/${name}.stories.tsx` : null %>"
---
import { <%= name %> } from "@/components/<%= path %>/<%= name %>";
import { ComponentMeta, ComponentStoryObj } from "@storybook/react";
export default { component: <%= name %> } as ComponentMeta<typeof <%= name %>>;
export const Index: ComponentStoryObj<typeof <%= name %>> = {
args: {},
};

next-seoの導入
titleタグやmetaタグ、OGPの設定、構造化マークアップ等をまとめて設定できる。
yarn add next-seo

Next.js 12 next/jest を利用したテストの導入
2022年10月現在、上記を参考に進めると以下のエラーが発生します。
Test environment jest-environment-jsdom cannot be found. Make sure the testEnvironment configuration option points to an existing node module.
Configuration Documentation:
https://jestjs.io/docs/configuration
As of Jest 28 "jest-environment-jsdom" is no longer shipped by default, make sure to install it separately.
上記エラーを読み進めるとjest-environment-jsdom
が必要ということなので、以下コマンドを入力してインストールします。
yarn add -D jest-environment-jsdom
セットアップされた Story をそのまま jest で再利用(render)可能にするcomposeStories関数を利用するために、@storybook/testing-react
もインストールします。
yarn add -D @storybook/testing-react

諸々は下記にまとめました。
このスクラップは2022/12/02にクローズされました