Closed10

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

おとのおとの

Node.jsのバージョン設定

2022年9月19日時点でNode.jsの安定バージョンは16.17.0
今回はnodenv経由で上記バージョンをインストールする。

※nodenv本体のインストール方法は下記が参考になりました。
https://zenn.dev/donchan922/articles/b08a66cf3cbbc5

  1. Node.jsの最新バージョンをインストールできるように、nodenvを更新する
brew upgrade node-build
  1. Node.jsのバージョン16.17.0をインストール
nodenv install 16.17.0
  1. プロジェクトのルートディレクトリで.node-versionを作成し、バージョンを指定する
nodenv local 16.17.0
  1. 上記バージョンでYarnが利用できるようにインストール
npm install -g yarn
おとのおとの

Tailwind CSSの導入

汎用的に利用できるCSSのclassを作る手間を減らすことを目的にTailwind CSSを導入する。
CSS設計のFLOCSSに馴染みがあったのと、purge機能が搭載しているのも採用理由の1つ。

  1. Tailwind CSSと関連パッケージのインストール
yarn add -D tailwindcss postcss autoprefixer
  1. Tailwind CSS関連の設定ファイルの作成
npx tailwindcss init -p
  1. 設定の追加(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: [],
};
  1. global.cssにTailwind CSSを読み込ませる
src/styles/globals.css
@import "tailwindcss/base";
@import "tailwindcss/components";
@import "tailwindcss/utilities";
  1. 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;
  },
};
おとのおとの

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"
  },
}

https://www.npmjs.com/package/tailwind-config-viewer

おとのおとの

TailWind CSSの設定をカスタマイズする

  1. 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: [],
};
  1. ブレイクポイントをカスタマイズする
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: [],
};
  1. HTMLタグに付与したTailwindCSSのclassの順番をファイル保存時に自動で並び替えてくれるようにする
yarn add -D prettier-plugin-tailwindcss

公式でも推奨されていました。
https://tailwindcss.com/blog/automatic-class-sorting-with-prettier

おとのおとの

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.js 12 next/jest を利用したテストの導入

https://zenn.dev/miruoon_892/articles/e42e64fbb55137

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にクローズされました