Todos los posts

Boilerplate para nextjs

Uno de los pasos mas importantes al iniciar un proyecto de nextJs es configurar una variedad de herramientas y un entorno que nos permita mantener de manera sencilla estándares en cuanto a nuestro código.

Uno de los pasos mas importantes al iniciar un proyecto de nextJs es configurar una variedad de herramientas y un entorno que nos permita mantener de manera sencilla estándares en cuanto a nuestro código. Por ello en este articulo te enseñare un par de herramientas y configuración que normalmente utilizo en mis proyectos
 
Puedes encontrar mi boilerplate en
nextts-boilerplate
Drakezair • Updated Nov 16, 2022

Tecnologías

  • React query: Manejar peticiones asíncronas
  • Valtio: Remplazo a redux
  • Hook form: Manejo de formularios
  • tailwind: framework css
  • cypress: Pruebas E2E
  • jest: Pruebas unitarias
  • Commitlint: Mantener convenciones en los mensajes para los commits
  • Husky: Hook para validar calidad de código antes de realizar un commit
  • lint y prettier: Mantén tu código limpio
  • storybook: Mantén documentado tu proyecto

Estructura de archivos

Una buena practica para nextJs o proyectos frontend en general es trabajar en módulos, haciendo una carpeta para cada bloque de código o componente, así podemos tener todo lo relacionado en el mismo lugar. Ej pruebas, documentación, formularios…
 
Por lo que recomiendo seguir la siguiente estructura:
  • [config files]
  • pages (NextJs routers)
    • page.tsx
  • src
    • modules
      • [Name]Module
        • [Name]Page
          • __tests__
          • UI
            • Layout
            • Components
            • Forms
          • Wrappers
          • [Name]Page.ts
        • index.ts (To export all pages of module)
    • lib
    • constants
    • types
    • hook
    • store

Comandos

yarn dev

Ejecuta la aplicación en el modo de desarrollo.\ Abra http://localhost:3000 para verlo en el navegador.
La página se volverá a cargar si realiza modificaciones.\ También verá cualquier error de pelusa en la consola.

yarn build

Construye la aplicación para producción en la carpeta build.\ Empaqueta correctamente React en modo de producción y optimiza la compilación para obtener el mejor rendimiento.
La compilación se minimiza y los nombres de archivo incluyen los hashes.\ ¡Tu aplicación está lista para ser implementada!
Consulte la sección sobre implementación para obtener más información.

yarn format

Formatee el estilo de codificación como text/plain para mantenerlo claro y estándar con más bonito

yarn lint

Consulta las reglas de calidad del código

yarn ready

Marque todos los pasos requeridos para poder hacer una confirmación

yarn cypress:open

Levanta el servidor Cypress en GUI para ver la prueba

yarn cypress:run

Levanta el servidor Cypress en CLI para ver la ejecución de la verificación de prueba

yarn storybook

Levanta servidor de storybook

build-storybook

Genera Build estático de storybook

postbuild

Genera sitemap

Detalles de configuración

1 - nextJs

  1. Iniciación proyecto
$ yarn create next-app my-app
notion image
  1. package.json
{
  "name": "boilerplate",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "dev": "next dev",
    "build": "next build",
    "start": "next start",
    "lint": "next lint",
    "lint:fix": "eslint src --fix && yarn format",
    "lint:strict": "eslint --max-warnings=0 src",
    "typecheck": "tsc --noEmit --incremental false",
    "test:watch": "jest --watch",
    "test": "jest",
    "format": "prettier -w .",
    "format:check": "prettier -c .",
    "postbuild": "next-sitemap --config next-sitemap.config.js",
    "prepare": "husky install && npx husky add .husky/pre-commit 'yarn ready' && git add .husky/pre-commit",
    "ready": "yarn lint:fix && yarn lint:strict && yarn typecheck && yarn format:check && yarn test",
    "cypress:open": "cypress open",
    "cypress:run": "cypress run",
    "storybook": "start-storybook -p 6006",
    "build-storybook": "build-storybook"
  },
  "dependencies": {
    "@types/node": "18.11.9",
    "@types/react-dom": "18.0.9",
    "next": "13.0.3",
    "react": "18.2.0",
    "react-dom": "18.2.0",
    "@tanstack/react-query": "^4.10.3",
    "@tanstack/react-query-devtools": "^4.14.5",
    "@hookform/error-message": "^2.0.0",
    "cypress-file-upload": "^5.0.8",
    "cypress-localstorage-commands": "^2.2.1",
    "graphql": "^16.6.0",
    "http-status-codes": "^2.2.0",
    "js-cookie": "^3.0.1",
    "msw": "^0.47.3",
    "next-auth": "^4.15.0",
    "nock": "^13.2.9",
    "react-hook-form": "^7.39.1",
    "react-icons": "^4.4.0",
    "react-router-dom": "6",
    "tailwind-merge": "^1.6.0",
    "valtio": "^1.7.5"
  },
  "devDependencies": {
    "@babel/core": "^7.19.6",
    "@commitlint/cli": "^16.3.0",
    "@commitlint/config-conventional": "^16.2.4",
    "@storybook/addon-actions": "^6.5.13",
    "@storybook/addon-essentials": "^6.5.13",
    "@storybook/addon-interactions": "^6.5.13",
    "@storybook/addon-links": "^6.5.13",
    "@storybook/addon-postcss": "^2.0.0",
    "@storybook/builder-webpack5": "^6.5.13",
    "@storybook/manager-webpack5": "^6.5.13",
    "@storybook/react": "^6.5.13",
    "@storybook/testing-library": "^0.0.13",
    "@svgr/webpack": "^6.3.1",
    "@tailwindcss/forms": "^0.5.3",
    "@testing-library/jest-dom": "^5.16.5",
    "@testing-library/react": "^13.4.0",
    "@types/react": "^18.0.20",
    "@typescript-eslint/eslint-plugin": "^5.37.0",
    "@typescript-eslint/parser": "^5.37.0",
    "autoprefixer": "^10.4.11",
    "babel-loader": "^8.2.5",
    "cypress": "^10.9.0",
    "cypress-mochawesome-reporter": "^3.2.3",
    "cypress-v10-preserve-cookie": "^1.2.1",
    "eslint": "^8.23.1",
    "eslint-config-next": "^12.3.0",
    "eslint-config-prettier": "^8.5.0",
    "eslint-plugin-simple-import-sort": "^7.0.0",
    "eslint-plugin-storybook": "^0.6.7",
    "eslint-plugin-unused-imports": "^2.0.0",
    "husky": "^7.0.4",
    "jest": "^27.5.1",
    "lint-staged": "^12.5.0",
    "next-router-mock": "^0.7.4",
    "next-sitemap": "^2.5.28",
    "postcss": "^8.4.16",
    "prettier": "^2.7.1",
    "prettier-plugin-tailwindcss": "^0.1.13",
    "react-test-renderer": "^18.2.0",
    "start-server-and-test": "^1.14.0",
    "tailwindcss": "^3.1.8",
    "ts-jest": "^29.0.3",
    "typescript": "4.9.0"
  },
  "lint-staged": {
    "!(cypress/**/*)!(**/*.test.*)**/*.{js,jsx,ts,tsx}": [
      "eslint --max-warnings=0",
      "prettier -w"
    ],
    "**/*.{json,css,scss,md}": [
      "prettier -w"
    ]
  },
  "resolutions": {
    "webpack": "^5"
  }
}
  1. Reinstalación node_modules
$ rm -rf node_modules && yarn
  1. Remplazar tsconfig.json
{
  "compilerOptions": {
    "target": "es5",
    "lib": ["dom", "dom.iterable", "esnext"],
    "allowJs": true,
    "skipLibCheck": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "noEmit": true,
    "esModuleInterop": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "jsx": "preserve",
    "baseUrl": ".",
    "types": ["cypress", "cypress-file-upload"],
    "paths": {
      "@/*": ["./src/*"],
      "@/styles/*": ["./styles/*"]
    },
    "incremental": true
  },
  "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", "src/types/*.d.ts"],
  "exclude": [
    "node_modules",
    "cypress",
    "amplify",
    "**/*.test.*",
    "azure-pipelines.yml",
    "backend",
    "bin"
  ],
  "moduleResolution": ["node_modules", ".next", "node"]
}
  1. next-sitemap.config.js
/**
 * @type {import('next-sitemap').IConfig}
 * @see https://github.com/iamvishnusankar/next-sitemap#readme
 */
module.exports = {
  // !STARTERCONF Change the siteUrl
  /** Without additional '/' on the end, e.g. https://theodorusclarence.com */
  siteUrl: 'https://tsnext-tw.thcl.dev',
  generateRobotsTxt: true,
  robotsTxtOptions: {
    policies: [{ userAgent: '*', allow: '/' }],
  },
};

2 - eslint y prettier

  1. Archivo eslintrc.js
module.exports = {
  env: {
    browser: true,
    es2021: true,
    node: true,
  },
  plugins: ['@typescript-eslint', 'simple-import-sort', 'unused-imports'],
  extends: [
    'eslint:recommended',
    'next',
    'next/core-web-vitals',
    'plugin:@typescript-eslint/recommended',
    'prettier',
    'plugin:storybook/recommended',
  ],
  rules: {
    'no-unused-vars': 'off',
    'no-console': 'warn',
    '@typescript-eslint/explicit-module-boundary-types': 'off',
    'react/display-name': 'off',
    'react/jsx-curly-brace-presence': [
      'warn',
      {
        props: 'never',
        children: 'never',
      },
    ],
    //#region  //*=========== Unused Import ===========
    '@typescript-eslint/no-unused-vars': 'off',
    'unused-imports/no-unused-imports': 'warn',
    'unused-imports/no-unused-vars': [
      'warn',
      {
        vars: 'all',
        varsIgnorePattern: '^_',
        args: 'after-used',
        argsIgnorePattern: '^_',
      },
    ],
    //#endregion  //*======== Unused Import ===========

    //#region  //*=========== Import Sort ===========
    'simple-import-sort/exports': 'warn',
    'simple-import-sort/imports': [
      'warn',
      {
        groups: [
          // Packages `react` related packages come first.
          ['^react', '^@?\\w'],
          // ext library & side effect imports
          ['^@?\\w', '^\\u0000'],
          // {s}css files
          ['^.+\\.s?css$'],
          // Lib and hooks
          ['^@/lib', '^@/hooks'],
          // static data
          ['^@/data'],
          // components
          ['^@/components', '^@/container'],
          // zustand store
          ['^@/store'],
          // Other imports
          ['^@/'],
          // relative paths up until 3 level
          [
            '^\\./?$',
            '^\\.(?!/?$)',
            '^\\.\\./?$',
            '^\\.\\.(?!/?$)',
            '^\\.\\./\\.\\./?$',
            '^\\.\\./\\.\\.(?!/?$)',
            '^\\.\\./\\.\\./\\.\\./?$',
            '^\\.\\./\\.\\./\\.\\.(?!/?$)',
          ],
          ['^@/types'],
          // other that didnt fit in
          ['^'],
        ],
      },
    ],
    //#endregion  //*======== Import Sort ===========
  },
  ignorePatterns: ['src/.storybook/*'],

  globals: {
    React: true,
    JSX: true,
  },
};
  1. Archivo .eslintignore
.\amplify
.\cypress
.\src\stories
!.stories
  1. Archivo .prettierrc.js
module.exports = {
  arrowParens: 'always',
  singleQuote: true,
  jsxSingleQuote: true,
  tabWidth: 2,
  semi: true,
};
  1. Archivo .prettierignore
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.

# dependencies
/node_modules
/.pnp
.pnp.js

# testing
/coverage

# next.js
.next
/.next/
/out/

# production
/build

# misc
.DS_Store
*.pem

# debug
npm-debug.log*
yarn-debug.log*
yarn-error.log*

# local env files
.env.local
.env.development.local
.env.test.local
.env.production.local

# vercel
.vercel

# changelog
CHANGELOG.md

# Others
/amplify
/cypress
/backend
cypress.config.ts
.github
.idea
.vscode
azure-pipelines.yml
src/graphql/shema.json
src/API.TS
./src/stories
./src/graphql/

3 - Cypress y Jest

  1. Archivo cypress.config.ts
import { defineConfig } from 'cypress';

export default defineConfig({
  projectId: 'AmplifyFirstTouch',
  reporter: 'cypress-mochawesome-reporter',
  reporterOptions: {
    reportDir: 'cypress/report/mochawesome-report',
    saveJson: true,
  },
  e2e: {
    baseUrl: 'http://localhost:3000',
    experimentalSessionAndOrigin: true,
    video: false,
    setupNodeEvents(on, config) {
      require('cypress-mochawesome-reporter/plugin')(on);
    }
  },
  component: {
    devServer: {
      framework: 'next',
      bundler: 'webpack',
    },
  },
});
  1. Archivo jest.config.js
// eslint-disable-next-line @typescript-eslint/no-var-requires
const nextJest = require('next/jest');

const createJestConfig = nextJest({
  // Provide the path to your Next.js app to load next.config.js and .env files in your test environment
  dir: './',
});

const { pathsToModuleNameMapper } = require('ts-jest');
const { compilerOptions } = require('./tsconfig');

// Add any custom config to be passed to Jest
const customJestConfig = {
  // Add more setup options before each test is run
  setupFilesAfterEnv: ['<rootDir>/jest.setup.js'],

  // if using TypeScript with a baseUrl set to the root directory then you need the below for alias' to work
  moduleDirectories: ['node_modules', '<rootDir>/'],

  testEnvironment: 'jest-environment-jsdom',

  /**
   * Absolute imports and Module Path Aliases
   */
  moduleNameMapper: {
    '^@/(.*)$': ['<rootDir>/src/$1'],
    '^~/(.*)$': '<rootDir>/public/$1',

    ...pathsToModuleNameMapper(compilerOptions.paths, { prefix: '<rootDir>/' }),
  },
};

// createJestConfig is exported this way to ensure that next/jest can load the Next.js config which is async
module.exports = createJestConfig(customJestConfig);
  1. Archivo jest.setup.js
import '@testing-library/jest-dom/extend-expect';

// Allow router mocks.
// eslint-disable-next-line no-undef
jest.mock('next/router', () => require('next-router-mock'));

4 - Tailwind

  1. Archivo tailwind.config.js
/* eslint-disable @typescript-eslint/no-var-requires */
const { fontFamily } = require('tailwindcss/defaultTheme');

/** @type {import('tailwindcss').Config} */
module.exports = {
  content: ['./src/**/*.{js,jsx,ts,tsx}'],
  theme: {
    extend: {
      fontFamily: {
        primary: ['Inter', ...fontFamily.sans],
      },
      colors: {
        primary: {
          // Customize it on globals.css :root
          50: 'rgb(var(--tw-color-primary-50) / <alpha-value>)',
          100: 'rgb(var(--tw-color-primary-100) / <alpha-value>)',
          200: 'rgb(var(--tw-color-primary-200) / <alpha-value>)',
          300: 'rgb(var(--tw-color-primary-300) / <alpha-value>)',
          400: 'rgb(var(--tw-color-primary-400) / <alpha-value>)',
          500: 'rgb(var(--tw-color-primary-500) / <alpha-value>)',
          600: 'rgb(var(--tw-color-primary-600) / <alpha-value>)',
          700: 'rgb(var(--tw-color-primary-700) / <alpha-value>)',
          800: 'rgb(var(--tw-color-primary-800) / <alpha-value>)',
          900: 'rgb(var(--tw-color-primary-900) / <alpha-value>)',
        },
        dark: '#222222',
      },
      keyframes: {
        flicker: {
          '0%, 19.999%, 22%, 62.999%, 64%, 64.999%, 70%, 100%': {
            opacity: 0.99,
            filter:
              'drop-shadow(0 0 1px rgba(252, 211, 77)) drop-shadow(0 0 15px rgba(245, 158, 11)) drop-shadow(0 0 1px rgba(252, 211, 77))',
          },
          '20%, 21.999%, 63%, 63.999%, 65%, 69.999%': {
            opacity: 0.4,
            filter: 'none',
          },
        },
        shimmer: {
          '0%': {
            backgroundPosition: '-700px 0',
          },
          '100%': {
            backgroundPosition: '700px 0',
          },
        },
      },
      animation: {
        flicker: 'flicker 3s linear infinite',
        shimmer: 'shimmer 1.3s linear infinite',
      },
    },
  },
  plugins: [require('@tailwindcss/forms')],
};

5 - Commitlint

  1. Archivo commitlint.config.js
module.exports = {
  extends: ['@commitlint/config-conventional'],
  rules: {
    //   TODO Add Scope Enum Here
    // 'scope-enum': [2, 'always', ['yourscope', 'yourscope']],
    'type-enum': [
      2,
      'always',
      [
        'feat',
        'fix',
        'docs',
        'chore',
        'style',
        'refactor',
        'ci',
        'test',
        'perf',
        'revert',
        'vercel',
      ],
    ],
  },
};