> Hello World !!!

     

@syaku

[Vite] Vite 시작하기 (feat. reactjs, typescript, eslint, jest)

Vite 시작하기

vite는 빌드 속도가 확실히 빠르다. 그것만으로 사용할 가치가 충분하다.

프로젝트 생성

$ npm install vite

---

✔ Project name: … reactjs-vite-template
✔ Select a framework: › React
✔ Select a variant: › TypeScript

프로젝트 실행

$ npm run dev
$ npm run build

EditorConfig

설치

vscode 플러그인 설치

설정

.editorconfig

# <https://github.com/facebook/react/blob/master/.editorconfig>
root = true

[*]
charset = utf-8
end_of_line = lf
indent_size = 2
indent_style = space
insert_final_newline = true
max_line_length = 80
trim_trailing_whitespace = true

[*.md]
max_line_length = 0
trim_trailing_whitespace = false

[COMMIT_EDITMSG]
max_line_length = 0

Prettier

editorconfig와 prettier는 비슷한 역할을 한다. 둘중 하나만 사용해도 된다.

설치

$ npm install --save-dev --save-exact prettier

vscode 플러그인 설치

설정

.prettierrc

{
  "printWidth": 80,
  "tabWidth": 2,
  "useTabs": false,
  "semi": true,
  "singleQuote": true,
  "trailingComma": "all",
  "bracketSpacing": false,
  "jsxBracketSameLine": true,
  "arrowParens": "always",
  "parser": "typescript"
}

StyleLint

스타일시트에 대한 코드 컨벤션을 지원한다.

설치

$ npm install --save-dev --save-exact stylelint stylelint-config-standard

vscode 플러그인 설치

설정

.stylelintrc

{
  "extends": "stylelint-config-standard",
  "rules": {
    "at-rule-empty-line-before": null
  }
}

Jest

Jest 기반으로 작성한 단위 테스트를 처리한다. testing-library은 효율적인 테스트를 위한 다양한 기능들을 제공한다.

설치

$ npm install --save-dev --save-exact \\
		jest \\
		@types/jest \\
		ts-jest \\
		@testing-library/jest-dom \\
		@testing-library/react \\
		@testing-library/user-event \\
		identity-obj-proxy \\
		jest-environment-jsdom

vscode 플러그인 설치

설정

jest.config.cjs

module.exports = {
  roots: ['<rootDir>/src/'],
  setupFilesAfterEnv: ['<rootDir>/src/setupTests.ts'],
  transform: {
    '^.+\\\\.(ts|tsx)$': 'ts-jest',
    '\\\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$':
      '<rootDir>/fileTransformer.cjs',
  },
  testMatch: ['**/__tests__/**/*.+(ts|tsx)', '**/?(*.)+(spec|test).+(ts|tsx)'],
  moduleNameMapper: {
    '\\\\.(css|less|sass|svg)$': 'identity-obj-proxy',
  },
  testEnvironment: 'jsdom',
};

fileTransformer.cjs

const path = require('path');

module.exports = {
  process(src, filename) {
    return 'module.exports = ' + JSON.stringify(path.basename(filename)) + ';';
  },
};

src/setupTests.ts

import '@testing-library/jest-dom';

package.json

실행할 수 있도록 설정을 추가한다.

"scripts": {
  "test": "jest"
},

ESLint

설치

typescript, perttier, react 플러그인도 함께 설치한다.

$ npm install --save-dev --save-exact \\
	eslint \\
	eslint-config-prettier \\
	eslint-plugin-jsx-a11y \\
	eslint-plugin-prettier \\
	eslint-plugin-react \\
	eslint-plugin-react-hooks \\
  eslint-plugin-import \\
  eslint-import-resolver-node \\
	eslint-import-resolver-typescript \\
	eslint-import-resolver-alias \\
	@typescript-eslint/eslint-plugin \\
	@typescript-eslint/parser \\
  eslint-plugin-jest

vscode 플러그인

https://marketplace.visualstudio.com/items?itemName=dbaeumer.vscode-eslint

설정

.eslintrc.cjs

module.exports = {
  root: true,
  env: {
    browser: true,
    node: true,
    es2020: true,
  },
  parserOptions: {
    sourceType: 'module',
    ecmaFeatures: {
      jsx: true,
    },
  },
  settings: {
    react: {
      version: 'detect',
    },
    'import/resolver': {
      node: {},
      alias: {
        map: [['@', './src']],
      },
      typescript: {},
    },
  },
  rules: {
    'no-console': 'off',
    'import/no-unresolved': ['error', {commonjs: true, amd: true}],
    'import/extensions': ['error', 'never', {packages: 'always'}],
    'import/no-extraneous-dependencies': ['error'],
    'jsx-a11y/label-has-for': [
      'error',
      {
        // components: ["Label"],
        required: {
          some: ['nesting', 'id'],
        },
        allowChildren: true,
      },
    ],
    'jsx-a11y/label-has-associated-control': [
      'error',
      {
        required: {
          some: ['nesting', 'id'],
        },
      },
    ],
    'jsx-a11y/click-events-have-key-events': ['off'],
    'jsx-a11y/mouse-events-have-key-events': ['off'],
    'jsx-a11y/anchor-is-valid': [
      'error',
      {
        components: ['Link'],
        specialLink: ['to', 'hrefLeft', 'hrefRight'],
        aspects: ['invalidHref'],
      },
    ],
    'react/jsx-filename-extension': ['error', {extensions: ['.tsx']}],
  },
  overrides: [
    {
      files: ['*.tsx', '*.ts'],
      parser: '@typescript-eslint/parser',
      extends: [
        'eslint:recommended',
        'plugin:@typescript-eslint/eslint-recommended',
        'plugin:@typescript-eslint/recommended',
        'plugin:@typescript-eslint/recommended-requiring-type-checking',
        'plugin:react/recommended',
        'plugin:react-hooks/recommended',
        'plugin:prettier/recommended',
        'plugin:import/typescript',
      ],
      plugins: [
        '@typescript-eslint',
        'import',
        'react',
        'react-hooks',
        'jsx-a11y',
        'prettier',
      ],
      parserOptions: {
        project: './tsconfig.json',
        createDefaultProgram: true,
      },
      settings: {
        'import/resolver': {
          typescript: {},
        },
      },
      rules: {
        'react/react-in-jsx-scope': 'off',
        'react-hooks/rules-of-hooks': 'error',
        'react-hooks/exhaustive-deps': 'warn',
        'react/prop-types': 'off',
      },
    },
    {
      files: ['(/__tests__/.*|(\\\\.|/)(test|spec))\\\\.[jt]sx?$'],
      plugins: ['jest'],
      extends: ['plugin:jest/recommended'],
      rules: {'jest/prefer-expect-assertions': 'off'},
    },
  ],
};
  • root - 상위 설정 파일 찾기 여부 (true 설정하면 찾지 않는 다)
  • env - 자바스크립트 언어의 전역 변수 정의 (https://eslint.org/docs/latest/user-guide/configuring/language-options)
  • globals - 전역 변수 정의
  • parserOptions
    • ecmaVersion - ECMA 버전 설정
    • sourceType - 소스 export 타입
    • ecmaFeatures - 사용하려는 추가 언어
      • globalReturn - 전역 문을 허용할지 여부를 파서에 알린다.
      • impliedStric - strict mode 사용 여부 (엄격한 규칙)
      • jsx - jsx 사용 여부

rule serverities

"off" or 0 - turn the rule off
"warn" or 1 - turn the rule on as a warning (doesn’t affect exit code)
"error" or 2 - turn the rule on as an error (exit code is 1 when triggered)

Typescript 설정

tsconfig.json

{
  "compilerOptions": {
    "target": "ESNext",
    "useDefineForClassFields": true,
    "lib": ["DOM", "DOM.Iterable", "ESNext"],
    "allowJs": false,
    "skipLibCheck": true,
    "esModuleInterop": false,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "module": "ESNext",
    "moduleResolution": "Node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "jsx": "react-jsx",
    "paths": {"@/*": ["./src/*"]},
    "typeRoots": ["./node_modules/@types", "./src/@types"]
  },
  "include": ["src", "setupTests.ts", "./src/@types"],
  "references": [{"path": "./tsconfig.node.json"}]
}

Vite ESLint 설정

import {defineConfig} from 'vite';
import react from '@vitejs/plugin-react';
import path from 'path';

export default defineConfig({
  plugins: [react()],
  resolve: {
    alias: {
      '@': path.resolve(__dirname, './src'),
    },
  },
});

VSCode 설정

.vscode/settings.json

{
  "typescript.validate.enable": true,
  "eslint.enable": true,
  "eslint.validate": [
    "javascript",
    "javascriptreact",
    "typescript",
    "typescriptreact"
  ],

  "eslint.alwaysShowStatus": true,
  "prettier.configPath": ".prettierrc",
  "editor.formatOnSave": true,
  "editor.codeActionsOnSave": {
    "source.fixAll.eslint": true
  },
  "[typescript]": {
    "editor.defaultFormatter": "esbenp.prettier-vscode"
  },
  "[typescriptreact]": {
    "editor.defaultFormatter": "esbenp.prettier-vscode"
  },
  "stylelint.validate": ["css"],
  "auto-close-tag.activationOnLanguage": [
    "xml",
    "javascriptreact",
    "typescriptreact",
    "plaintext",
    "markdown",
    "HTML (Eex)"
  ]
}

MUI 설치

https://mui.com/material-ui/getting-started/installation/

$ npm install --save-dev --save-exact \\
	@mui/material \\
	@emotion/react \\
	@emotion/styled \\
	@mui/icons-material

Svg 사용하기

설치

$ npm install -D --save-exact vite-plugin-svgr

설정

vite.config.js

import svgr from 'vite-plugin-svgr';

export default {
  plugins: [svgr()],
}

추가 이슈사항

'".svg"' 모듈에 내보낸 멤버 'ReactComponent'이(가) 없습니다. 대신 '".svg"에서 ReactComponent 가져오기'를 사용하시겠습니까?ts(2614)

./src/@types/media-type.d.ts

declare module '*.svg' {
  import React = require('react');
  export const ReactComponent: React.FC<React.SVGProps<SVGSVGElement>>;
  const src: string;
  export default src;
}

tsconfig.json

"include": ["src", "setupTests.ts", "./src/@types"],

'Tech' 카테고리의 다른 글

SFTP 터널링 접속  (0) 2022.12.26
[Nginx] 403 Forbidden / Permission denied 해결  (0) 2022.12.22
Spring Security OAuth with JWT  (0) 2021.11.11
Spring Security OAuth - Resource Server  (0) 2021.11.11