Skip to main content

Setup Next.js Project With Typescript + ESLint + Prettier + Ant Design

Kongvut Sangkla

Intro

บทความนี้จะเป็นการติดตั้ง Next.js ที่เป็น TypeScript รวมกับ ESLint Prettier และ Ant Design โดย ESLint จะเป็น Linter ที่จะแนะนำให้เราเขียนโค้ดตามมาตรฐาน ส่วน Prettier คือตัวช่วยที่ในการเขียนโค้ดเราดูสวยมากขึ้น อ่านง่ายมากขึ้น และยังช่วยในการจัดฟอร์แมตอัตโนมัติ และสุดท้าย Ant Design คือ Frontend Framework ที่ช่วยให้นักพัฒนาออกแบบ UI ได้ สวยงาม ง่ายและรวดเร็ว โดยมี Component ต่าง ๆ มากมายให้เลือกใช้เยอะมาก

ติดตั้ง Next.js

  1. ติดตั้ง Next.js

    CLI
    yarn create next-app next.js-with-typescript-eslint-prettier-ant-design

ติดตั้ง ESLint และ Prettier

  1. ติดตั้ง ESLint และ Prettier

    CLI
    yarn add --dev eslint prettier eslint-plugin-react eslint-plugin-react-hooks eslint-config-prettier eslint-plugin-prettier eslint-plugin-jsx-a11y
    1. สร้าง Cofig Files สำหรับ ESLint

      CLI
      touch .eslintrc.js .prettierrc
    2. กำหนด .prettierrc ดังนี้

      .prettierrc
      {
      "semi": false,
      "tabWidth": 2,
      "printWidth": 140,
      "singleQuote": true,
      "trailingComma": "none",
      "jsxBracketSameLine": true
      }
    3. กำหนด .eslintrc.js ดังนี้

      .eslintrc.js
      module.exports = {
      root: true, // Make sure eslint picks up the config at the root of the directory
      parserOptions: {
      ecmaVersion: 2020, // Use the latest ecmascript standard
      sourceType: 'module', // Allows using import/export statements
      project: './tsconfig.json',
      createDefaultProgram: true,
      ecmaFeatures: {
      jsx: true // Enable JSX since we're using React
      }
      },
      settings: {
      react: {
      version: 'detect' // Automatically detect the react version
      }
      },
      env: {
      browser: true, // Enables browser globals like window and document
      amd: true, // Enables require() and define() as global variables as per the amd spec.
      node: true // Enables Node.js global variables and Node.js scoping.
      },
      extends: [
      'eslint:recommended',
      'plugin:react/recommended',
      'plugin:jsx-a11y/recommended',
      'plugin:prettier/recommended' // Make this the last element so prettier config overrides other formatting rules
      ],
      rules: {
      'prettier/prettier': ['error', {}, { usePrettierrc: true }]
      }
      };
    4. สร้าง Ignore Files ของ ESLint

      1. คำสั่งสำหรับสร้างไฟล์

        CLI
        touch .eslintignore .prettierignore
      2. เพิ่ม Folders หรือ Files ไว้ใน .eslintrc.js และ .prettierrc ตามต้องการเพื่อไม่ให้ ESLint และ Prettier สนใจ

        .eslintrc.js และ .prettierrc
        # dependencies
        /node_modules
        /.pnp
        .pnp.js

        # testing
        /coverage

        # next.js
        /.next/
        /out/

        # production
        /build
        Tips

        กรณีต้องการใช้ .gitignore แทนให้เพิ่มคำสั่งนี้ตอนรัน eslint --fix . --ignore-path ./.gitignore

  2. กำหนดคำสั่งสำหรับการสั่งรัน

    1. ที่ไฟล์ package.json เพิ่มส่วนของ lint และ format ดังนี้

      package.json
      "scripts": {
      "dev": "next dev",
      "build": "next build",
      "start": "next start",
      "lint": "eslint --fix .",
      "format": "prettier --write './**/*.{js,jsx,ts,tsx,css,md,json}' --config ./.prettierrc"
      }
    2. ทดสอบรันคำสั่ง yarn lint หรือ yarn format

  3. สำหรับ Next.js ให้เพิ่ม Rules ที่ไฟล์ .eslintrc.js ดังนี้

    .eslintrc.js
    rules: {
    'jsx-a11y/anchor-is-valid': [
    'error',
    {
    components: ['Link'],
    specialLink: ['hrefLeft', 'hrefRight'],
    aspects: ['invalidHref', 'preferButton']
    }
    ],
    '@typescript-eslint/explicit-function-return-type': 0,
    'react-hooks/rules-of-hooks': 0,
    'react/react-in-jsx-scope': 0,
    'react/prop-types': 0,
    'react/jsx-filename-extension': 0,
    'react/destructuring-assignment': 0,
    'no-nested-ternary': 0,
    'array-callback-return': 0,
    'consistent-return': 0,
    'no-param-reassign': 0,
    'lines-between-class-members': 0
    }

ติดตั้ง TypeScript

  1. ติดตั้ง TypeScript

    CLI
    yarn add --dev typescript @types/react @types/node @typescript-eslint/eslint-plugin @typescript-eslint/parser
  2. สร้างไฟล์ Config ของ TypeScript

    CLI
    touch tsconfig.json
  3. กำหนดค่าของ tsconfig.json ดังนี้

    tsconfig.json
    {
    "compilerOptions": {
    "target": "es5",
    "lib": ["dom", "dom.iterable", "esnext"],
    "allowJs": true,
    "skipLibCheck": true,
    "strict": false,
    "forceConsistentCasingInFileNames": true,
    "noEmit": true,
    "esModuleInterop": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "jsx": "preserve"
    },
    "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx"],
    "exclude": ["node_modules"]
    }
  4. แก้ไขไฟล์ .eslintrc.js เพิ่ม

    .eslintrc.js
    module.exports = {
    plugins: ['react', '@typescript-eslint'],
    parser: '@typescript-eslint/parser',
    parserOptions: {
    ...,
    project: './tsconfig.json',
    ...
    }
    };
  5. จากนั้นเพิ่มในส่วนของ Extends

    .eslintrc.js
    // ...
    {
    extends: [
    'plugin:@typescript-eslint/eslint-recommended',
    'plugin:@typescript-eslint/recommended',
    'next',
    'next/core-web-vitals'
    ]
    }

ติดตั้ง Ant Design

  1. ติดตั้ง Ant Design

    CLI
    yarn add --dev antd @ant-design/icons babel-plugin-import less next-plugin-antd-less
  2. สร้างไฟล์สำหรับการตั้งค่า

    CLI
    touch .babelrc.js next.config.js styles/antd-custom.less
  3. ไฟล์ styles/antd-custom.less กำหนด Custom style ของ Ant Design ดังนี้

    styles/antd-custom.less
    @import '~antd/lib/style/themes/default.less';

    @primary-color: #910079; // primary color for all components
    @link-color: #1890ff; // link color
    @success-color: #52c41a; // success state color
    @warning-color: #faad14; // warning state color
    @error-color: #f5222d; // error state color
    @font-size-base: 16px; // major text font size
    @font-family: Prompt, -apple-system, BlinkMacSystemFont, "Segoe UI",
    Roboto, "Helvetica Neue", Arial, "Noto Sans", sans-serif, "Apple Color Emoji",
    "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji";
    @heading-color: rgba(0, 0, 0, 0.85); // heading text color
    @text-color: rgba(0, 0, 0, 0.65); // major text color
    @text-color-secondary: rgba(0, 0, 0, 0.45); // secondary text color
    @disabled-color: rgba(0, 0, 0, 0.25); // disable state color
    @border-radius-base: 8px; // major border radius
    @border-color-base: #d9d9d9; // major border color
    @box-shadow-base: 0 3px 6px -4px rgba(0, 0, 0, 0.12),
    0 6px 16px 0 rgba(0, 0, 0, 0.08), 0 9px 28px 8px rgba(0, 0, 0, 0.05); // major shadow for layers

    // LINK
    @link-color: #405887;
    @link-hover-color: #1c2539;
    @link-active-color: #848484;
    @link-decoration: none;
    @link-hover-decoration: underline;
    @link-focus-decoration: underline;
    @link-focus-outline: 0;

    // Layout
    @layout-body-background: #f0f2f5;
    @layout-header-background: #b80b6b;
  4. ไฟล์ .babelrc.js กำหนดค่าดังนี้

    .babelrc.js
    module.exports = {
    presets: [['next/babel']],
    plugins: [['import', { libraryName: 'antd', style: true }]]
    }
  5. ไฟล์ next.config.js กำหนดค่าดังนี้

    next.config.js
    /* eslint-disable */
    const withAntdLess = require('next-plugin-antd-less');

    module.exports = withAntdLess({
    lessVarsFilePath: './styles/antd-custom.less',
    cssLoaderOptions: {
    // https://github.com/webpack-contrib/css-loader#object
    //
    // sourceMap: true, // default false
    // esModule: false, // default false
    // modules: {
    // exportLocalsConvention: 'asIs',
    // exportOnlyLocals: true,
    // mode: 'pure',
    // getLocalIdent: [Function: getCssModuleLocalIdent]
    // }
    },
    // Other Config Here...

    webpack(config) {
    return config;
    }
    });
note

อย่าลืมเปลี่ยนนามสกุลไฟล์ในโฟลเดอร์ pages เป็น ts และ tsx

ทดสอบการทำงาน

ทดสอบสำหรับโหมด Development

CLI
next dev

ทดสอบเข้าผ่าน URL http://localhost:3000

Project ตัวอย่างบน GitHub

https://github.com/kongvut/example-next-js-with-typescript-eslint-prettier-ant-design

Loading...