코딩기록

vscode로 eslint + prettier + 리액트 타입스크립트 프로젝트 생성 본문

프론트/리액트

vscode로 eslint + prettier + 리액트 타입스크립트 프로젝트 생성

뽀짝코딩 2025. 2. 4. 00:22
728x90

익스텐션에서 prettier, Eslint를 설치 한다.

[ .prettierrc ]

{
  "arrowParens": "avoid",
  "bracketSpacing": true,
  "htmlWhitespaceSensitivity": "css",
  "insertPragma": false,
  "jsxBracketSameLine": false,
  "jsxSingleQuote": false,
  "printWidth": 120,
  "proseWrap": "preserve",
  "quoteProps": "as-needed",
  "requirePragma": false,
  "semi": true,
  "singleQuote": false,
  "tabWidth": 2,
  "trailingComma": "es5",
  "useTabs": false,
  "vueIndentScriptAndStyle": false,
  "endOfLine": "crlf"
}

 

 

{
"arrowParens": "always", // 화살표 함수의 매개변수가 하나일 때 괄호를 사용할지 여부
"bracketSpacing": true, // 객체 리터럴에서 중괄호 내부에 공백 삽입할지 여부
"endOfLine": "auto", // EoF 방식, OS별로 처리 방식이 다름
"htmlWhitespaceSensitivity": "css", // HTML 공백 감도 설정
"jsxBracketSameLine": false, // JSX의 마지막 `>`를 다음 줄로 내릴지 여부
"jsxSingleQuote": false, // JSX에 singe 쿼테이션 사용 여부
"printWidth": 80, // 한 줄에 출력되는 코드의 최대 길이
"proseWrap": "preserve", // markdown 텍스트의 줄바꿈 방식 (v1.8.2)
"quoteProps": "as-needed" // 객체 속성에 쿼테이션 적용 방식
"semi": true, // 세미콜론 사용 여부
"singleQuote": true, // single 쿼테이션 사용 여부
"tabWidth": 2, // 탭 간격
"trailingComma": "all", // 여러 줄을 사용할 때, 후행 콤마 사용 방식
"useTabs": false, // 탭 사용 여부
"vueIndentScriptAndStyle": true, // Vue 파일의 script와 style 태그의 들여쓰기 여부 (v1.19.0)
"parser": '', // 사용할 parser를 지정, 자동으로 지정됨
"filepath": '', // parser를 유추할 수 있는 파일을 지정
"rangeStart": 0, // 포맷팅을 부분 적용할 파일의 시작 라인 지정
"rangeEnd": Infinity, // 포맷팅 부분 적용할 파일의 끝 라인 지정,
"requirePragma": false, // 파일 상단에 미리 정의된 주석을 작성하고 Pragma로 포맷팅 사용 여부 지정
"insertPragma": false, // 미리 정의된 @format marker의 사용 여부 (v1.8.0)
 "overrides": [
    {
      "files": "*.json",
      "options": {
        "printWidth": 200
      }
    }
  ], // 특정 파일별로 옵션을 다르게 지정함, ESLint 방식 사용
}

 

[ .eslintrc.json ] 

{
  "parser": "@typescript-eslint/parser",
  "plugins": ["@typescript-eslint", "react", "jsx-a11y", "import", "prettier"],
  "extends": [
    // Prettier 설정을 ESLint에서 자동으로 적용
    "eslint:recommended",
    "plugin:@typescript-eslint/recommended",
    "plugin:react/recommended",
    "plugin:import/errors",
    "plugin:import/warnings",
    "plugin:import/typescript",
    "next/core-web-vitals",
    "plugin:prettier/recommended"
  ],
  "rules": {
    "prettier/prettier": "error",
    "react/react-in-jsx-scope": "off",
    // 미사용 변수 경고 끄기 - no-unused-vars
    "@typescript-eslint/no-unused-vars": "off",
    // ["error", { "argsIgnorePattern": "^_" }],
    "import/order": [
      2, // 2=error의미 1=warn 0=off비활성화
      {
        "groups": ["builtin", "external", "internal", "parent", "sibling", "index"],
        "newlines-between": "always"
      }
    ]
  },
  "settings": {
    "react": {
      "version": "detect"
    }
  }
}

 

 

[ tsconfig.json ] 

/* 특정 파일에서만 비활성화
     eslint-disable @typescript-eslint/no-unused-vars
   특정 코드에서만 비활성화
     eslint-disable-next-line @typescript-eslint/no-unused-vars
*/
{
  "compilerOptions": {
    "jsx": "react-jsx",
    /* Visit https://aka.ms/tsconfig to read more about this file */

    /* Projects */
    // "incremental": true,                              /* Save .tsbuildinfo files to allow for incremental compilation of projects. */
    // "composite": true,                                /* Enable constraints that allow a TypeScript project to be used with project references. */
    // "tsBuildInfoFile": "./.tsbuildinfo",              /* Specify the path to .tsbuildinfo incremental compilation file. */
    // "disableSourceOfProjectReferenceRedirect": true,  /* Disable preferring source files instead of declaration files when referencing composite projects. */
    // "disableSolutionSearching": true,                 /* Opt a project out of multi-project reference checking when editing. */
    // "disableReferencedProjectLoad": true,             /* Reduce the number of projects loaded automatically by TypeScript. */

    /* Language and Environment */
    "target": "es2016" /* "es5"         Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */,
    "lib": [
      "dom",
      "dom.iterable",
      "esnext"
    ] /* Specify a set of bundled library declaration files that describe the target runtime environment. */,
    // "jsx": "preserve",                                /* Specify what JSX code is generated. */
    // "experimentalDecorators": true,                   /* Enable experimental support for TC39 stage 2 draft decorators. */
    // "emitDecoratorMetadata": true,                    /* Emit design-type metadata for decorated declarations in source files. */
    // "jsxFactory": "",                                 /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'. */
    // "jsxFragmentFactory": "",                         /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */
    // "jsxImportSource": "",                            /* Specify module specifier used to import the JSX factory functions when using 'jsx: react-jsx*'. */
    // "reactNamespace": "",                             /* Specify the object invoked for 'createElement'. This only applies when targeting 'react' JSX emit. */
    // "noLib": true,                                    /* Disable including any library files, including the default lib.d.ts. */
    // "useDefineForClassFields": true,                  /* Emit ECMAScript-standard-compliant class fields. */
    // "moduleDetection": "auto",                        /* Control what method is used to detect module-format JS files. */

    /* Modules */
    "module": "commonjs" /* "esnext"     Specify what module code is generated. */,
    // "rootDir": "./",                                  /* Specify the root folder within your source files. */
    "moduleResolution": "node" /* Specify how TypeScript looks up a file from a given module specifier. */,
    // "baseUrl": "./",                                  /* Specify the base directory to resolve non-relative module names. */
    // "paths": {},                                      /* Specify a set of entries that re-map imports to additional lookup locations. */
    // "rootDirs": [],                                   /* Allow multiple folders to be treated as one when resolving modules. */
    // "typeRoots": [],                                  /* Specify multiple folders that act like './node_modules/@types'. */
    // "types": [],                                      /* Specify type package names to be included without being referenced in a source file. */
    // "allowUmdGlobalAccess": true,                     /* Allow accessing UMD globals from modules. */
    // "moduleSuffixes": [],                             /* List of file name suffixes to search when resolving a module. */
    "resolveJsonModule": true /* Enable importing .json files. */,
    // "noResolve": true,                                /* Disallow 'import's, 'require's or '<reference>'s from expanding the number of files TypeScript should add to a project. */

    /* JavaScript Support */
    "allowJs": true /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */,
    // "checkJs": true,                                  /* Enable error reporting in type-checked JavaScript files. */
    // "maxNodeModuleJsDepth": 1,                        /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */

    /* Emit */
    // "declaration": true,                              /* Generate .d.ts files from TypeScript and JavaScript files in your project. */
    // "declarationMap": true,                           /* Create sourcemaps for d.ts files. */
    // "emitDeclarationOnly": true,                      /* Only output d.ts files and not JavaScript files. */
    // "sourceMap": true,                                /* Create source map files for emitted JavaScript files. */
    // "outFile": "./",                                  /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */
    // "outDir": "./",                                   /* Specify an output folder for all emitted files. */
    // "removeComments": true,                           /* Disable emitting comments. */
    "noEmit": true /* Disable emitting files from a compilation. */,
    // "importHelpers": true,                            /* Allow importing helper functions from tslib once per project, instead of including them per-file. */
    // "importsNotUsedAsValues": "remove",               /* Specify emit/checking behavior for imports that are only used for types. */
    // "downlevelIteration": true,                       /* Emit more compliant, but verbose and less performant JavaScript for iteration. */
    // "sourceRoot": "",                                 /* Specify the root path for debuggers to find the reference source code. */
    // "mapRoot": "",                                    /* Specify the location where debugger should locate map files instead of generated locations. */
    // "inlineSourceMap": true,                          /* Include sourcemap files inside the emitted JavaScript. */
    // "inlineSources": true,                            /* Include source code in the sourcemaps inside the emitted JavaScript. */
    // "emitBOM": true,                                  /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */
    // "newLine": "crlf",                                /* Set the newline character for emitting files. */
    // "stripInternal": true,                            /* Disable emitting declarations that have '@internal' in their JSDoc comments. */
    // "noEmitHelpers": true,                            /* Disable generating custom helper functions like '__extends' in compiled output. */
    // "noEmitOnError": true,                            /* Disable emitting files if any type checking errors are reported. */
    // "preserveConstEnums": true,                       /* Disable erasing 'const enum' declarations in generated code. */
    // "declarationDir": "./",                           /* Specify the output directory for generated declaration files. */
    // "preserveValueImports": true,                     /* Preserve unused imported values in the JavaScript output that would otherwise be removed. */

    /* Interop Constraints */
    // "isolatedModules": true /* Ensure that each file can be safely transpiled without relying on other imports. */,
    "allowSyntheticDefaultImports": true /* Allow 'import x from y' when a module doesn't have a default export. */,
    "esModuleInterop": true /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */,
    // "preserveSymlinks": true,                         /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */
    "forceConsistentCasingInFileNames": true /* Ensure that casing is correct in imports. */,

    /* Type Checking */
    "strict": true /* Enable all strict type-checking options. */,
    // "noImplicitAny": true,                            /* Enable error reporting for expressions and declarations with an implied 'any' type. */
    "strictNullChecks": false /* When type checking, take into account 'null' and 'undefined'. */,
    // "strictFunctionTypes": true,                      /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */
    // "strictBindCallApply": true,                      /* Check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */
    // "strictPropertyInitialization": true,             /* Check for class properties that are declared but not set in the constructor. */
    // "noImplicitThis": true,                           /* Enable error reporting when 'this' is given the type 'any'. */
    // "useUnknownInCatchVariables": true,               /* Default catch clause variables as 'unknown' instead of 'any'. */
    // "alwaysStrict": true,                             /* Ensure 'use strict' is always emitted. */
    "noUnusedLocals": false /* 미사용 지역변수 경고 Enable error reporting when local variables aren't read. */,
    "noUnusedParameters": false /* 미사용 함수 매개변수 경고   Raise an error when a function parameter isn't read. */,
    // "exactOptionalPropertyTypes": true,               /* Interpret optional property types as written, rather than adding 'undefined'. */
    // "noImplicitReturns": true,                        /* Enable error reporting for codepaths that do not explicitly return in a function. */
    "noFallthroughCasesInSwitch": true /* Enable error reporting for fallthrough cases in switch statements. */,
    // "noUncheckedIndexedAccess": true,                 /* Add 'undefined' to a type when accessed using an index. */
    // "noImplicitOverride": true,                       /* Ensure overriding members in derived classes are marked with an override modifier. */
    // "noPropertyAccessFromIndexSignature": true,       /* Enforces using indexed accessors for keys declared using an indexed type. */
    // "allowUnusedLabels": true,                        /* Disable error reporting for unused labels. */
    // "allowUnreachableCode": true,                     /* Disable error reporting for unreachable code. */

    /* Completeness */
    // "skipDefaultLibCheck": true,                      /* Skip type checking .d.ts files that are included with TypeScript. */
    "skipLibCheck": true /* Skip type checking all .d.ts files. */
  },
  "include": ["src"]
}

 

[ setting.json ]

{
  "editor.formatOnType": true, // 타이핑할 때도 포맷 적용
  "editor.formatOnPaste": true, // 붙여넣기 시 포맷 적용

  // Enable per-language
  "editor.formatOnSave": true, // 저장할 때 자동으로 포맷 적용
  "editor.defaultFormatter": "esbenp.prettier-vscode", // Prettier를 기본 포맷터로 설정
  "[javascript]": {
    "editor.formatOnSave": true,
    "editor.defaultFormatter": "esbenp.prettier-vscode" // JavaScript 파일에서 Prettier 사용
  },
  "[typescriptreact]": {
    "editor.formatOnSave": true,
    "editor.defaultFormatter": "esbenp.prettier-vscode" // TypeScript React 파일에서 Prettier 사용
  },
  "[html]": {
    "editor.formatOnSave": true,
    "editor.defaultFormatter": "vscode.html-language-features"
  },

  // ESLint와 Prettier를 동시에 사용할 경우, ESLint의 수정도 적용
  "eslint.workingDirectories": [{ "mode": "auto" }],
  "editor.codeActionsOnSave": {
    "source.fixAll.eslint": "always"
  },
  // 파일 저장 후 Prettier로 포맷을 자동으로 적용하는 추가 설정
  "files.autoSave": "onWindowChange", // 자동 저장 설정 (필요한 경우)
  "eslint.validate": [
    "javascript",
    "javascriptreact",
    "typescript",
    "typescriptreact"
  ],

  // 기타 설정
  "workbench.startupEditor": "none",
  "editor.linkedEditing": true,
  "explorer.confirmDragAndDrop": false,
  "explorer.confirmDelete": false,

  // YAML 설정
  "yaml.schemas": {
    "file:///c%3A/Users/Pack/.vscode/extensions/atlassian.atlascode-3.0.10/resources/schemas/pipelines-schema.json": "bitbucket-pipelines.yml"
  },

  // Live Sass
  "liveSassCompile.settings.generateMap": false,
  "liveSassCompile.settings.formats": [
    {
      "format": "expanded",
      "extensionName": ".css",
      "savePath": "~/../css"
    }
  ],
  "liveSassCompile.settings.autoprefix": [],
  "liveSassCompile.settings.excludeList": ["/node_modules/**", "/.vscode/**"],

  // Live Server 관련 설정
  "liveServer.settings.donotShowInfoMsg": true,
  "liveServer.settings.useLocalIp": true,
  "liveServer.settings.donotVerifyTags": true,
  "liveServer.settings.ChromeDebuggingAttachment": false,
  "liveServer.settings.port": 3000,

  // 기타 에디터 설정
  "diffEditor.ignoreTrimWhitespace": true,
  "editor.tabSize": 2,
  "editor.detectIndentation": false,
  "editor.stickyScroll.enabled": false,
  "editor.minimap.renderCharacters": false,
  "editor.minimap.enabled": false,
  "workbench.editor.enablePreview": false,
  "editor.fontSize": 13,
  "window.zoomLevel": 1,
  "explorer.confirmPasteNative": false,
  "files.autoSaveDelay": 600,

  // Git 설정
  "git.confirmSync": false,

  // 접근성 관련
  "accessibility.signals.chatRequestSent": { "sound": "off" },
  "accessibility.signals.chatResponseReceived": { "sound": "off" },
  "editor.accessibilitySupport": "off",

  // 기타 유용한 설정
  "javascript.updateImportsOnFileMove.enabled": "always",
  "typescript.updateImportsOnFileMove.enabled": "always",

  // 사용자 단어
  "cSpell.userWords": ["kakao", "Nums"],

  // 파일 탐색기 설정
  "workbench.activityBar.location": "bottom",
  "notebook.formatOnSave.enabled": true,

  // 인라인 힌트
  "javascript.inlayHints.parameterNames.suppressWhenArgumentMatchesName": false,
  "editor.hover.above": false,
  "chat.commandCenter.enabled": false
}

 

 

변경 전

  return (
    <>
      <div>Hello React</div>
            				{/* <Clock /> */}
      {/* <Composition name="Abigail" /> */}
      <Extraction
        avatarUrl={comment.author.avatarUrl}  name={comment.author.name}
        text={comment.text} date={comment.date}
              />
    </>
  );

 

 

변경 후

  return (
    <>
      <div>Hello React</div>
      {/* <Clock /> */}
      {/* <Composition name="Abigail" /> */}
      <Extraction
        avatarUrl={comment.author.avatarUrl}
        name={comment.author.name}
        text={comment.text}
        date={comment.date}
      />
    </>
  );

 

ctrl + s 누르면 자동으로 저장되면서 정렬이 된다. 

만약 안된다면 아래 명령어로 ESLint를 수동으로 실행해서 확인해보자.

명령어 -  npx eslint --fix .

 

ESLint와 Prettier 패키지를 설치 명령어

npm install --save-dev eslint-plugin-prettier eslint-config-prettier

 

 

 

설정 파일들을 변경한 후에는 항상 vscode를 재시작해야한다.

그래도 안되면 아래 방법을 쓰자.

ESLint 플러그인 활성화 확인

  • Ctrl + Shift + P → "ESLint: Restart ESLint Server" 실행
  • Ctrl + Shift + P → "ESLint: Show Output Channel" 실행 후 오류 메시지가 있는지 확인

 

그래도 안된다면? 쳇지피에게 모든 설정파일을 복붙해서 물어보자  이런 부분에서는 유용하다.

 

 

 

 

 

 

 

 

 

 

 

반응형
Comments