tip-archive icon indicating copy to clipboard operation
tip-archive copied to clipboard

Absolute path in VSCode with TypeScript, CRA, Jest (feat. craco)

Open JaeYeopHan opened this issue 4 years ago โ€ข 2 comments

Description

Configure Absolute path!!๐Ÿš€

โ›‘ Based "react-scripts": "3.0.1"

TL;DR

Env

  • CRA (create-react-app)
  • TypeScript
  • Jest
  • craco (https://github.com/sharegate/craco)

Configuration

craco.config.js

const resolve = arg => path.resolve(__dirname, arg)

module.exports = function() {
  return {
    webpack: {
      alias: {
        '@': resolve('src'),
      },
    },
    jest: {
      configure: {
        moduleNameMapper: {
          '^@/(.*)$': '<rootDir>/src/$1',
        },
      },
    },
  }
}

tsconfig.paths.json

{
  "compilerOptions": {
    "baseUrl": "./",
    "paths": {
      "@/*": ["src/*"]
    }
  }
}

tsconfig.json

{
  "extends": "./tsconfig.paths.json",
  "compilerOptions": {
    "target": "es5",
    "lib": ["dom", "dom.iterable", "esnext"],
    "allowJs": true,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "jsx": "preserve",
    "plugins": [
      {
        "transform": "ts-optchain/transform"
      }
    ]
  },
  "include": ["src/*", "src/__tests__"]
}

Mine ๐Ÿ’ฃ

1. moduleNameMapper

CRA๋กœ ๊ฐœ๋ฐœ ํ™˜๊ฒฝ์œผ๋กœ ์„ธํŒ…์„ ํ•  ๊ฒฝ์šฐ, jest config๋ฅผ package.json์—์„œ override ํ•  ๋•Œ moduleNameMapper ์†์„ฑ์„ override ํ•  ์ˆ˜ ์—†๋‹ค. override ํ•˜๋ ค๋ฉด eject๋ฅผ ํ•˜๋ผ๊ณ  ํ•œ๋‹ค. ์™œ ๋•Œ๋ฌธ์— ์ด ์ค‘์š”ํ•œ ์†์„ฑ์„ ๋ง‰์•„๋†“์•˜๋Š”์ง€ ์ดํ•ด๊ฐ€ ๋˜์ง€ ์•Š๋Š” ๋ถ€๋ถ„. ๊ทธ๋ ‡๊ธฐ ๋•Œ๋ฌธ์— craco ์™€ ๊ฐ™์€ cra override tool์ด ํ•„์ˆ˜.

2. With Jest

test directory์— ๋Œ€ํ•œ ๋ถ€๋ถ„์„ ์ถ”๊ฐ€์ ์œผ๋กœ ๋ช…์‹œํ•ด์•ผ ํ•œ๋‹ค๋Š” ์ ์—์„œ ๊ธด ์‹œ๊ฐ„ ์‚ฝ์งˆ์„ ํ–ˆ๋‹ค. ํ…Œ์ŠคํŠธ ๋””๋ ‰ํ† ๋ฆฌ๊ฐ€ ๋‹ค๋ฅด๋‹ค๋ฉด include์— ์ถ”๊ฐ€ํ•ด์ค˜์•ผ ํ•œ๋‹ค.

3. Customize tsconfig.json

tsconfig.json ์—์„œ path ๊ด€๋ จํ•œ ์†์„ฑ์„ ๋ฐ”๋กœ ์ž‘์„ฑ์„ ํ•˜๋ฉด cra๊ฐ€ ์—†์• ๋ฒ„๋ฆฌ๊ณ  tscofnig.json์„ ๋‹ค์‹œ ์ƒ์„ฑํ•œ๋‹ค. ์ด ๋ถ€๋ถ„๋„ ์–ด๋–ค ์Šคํฌ๋ฆฝํŠธ์—์„œ ์ฒ˜๋ฆฌํ•˜๋Š”์ง€ ์ •ํ™•ํžˆ ํŒŒ์•…ํ•˜์ง€๋Š” ๋ชปํ–ˆ์ง€๋งŒ ์ด๋ฅผ ์šฐํšŒํ•˜๋Š” ๋ฐฉ๋ฒ•์€ ์กด์žฌํ•œ๋‹ค. ๋ณ„๋„ ํŒŒ์ผ๋กœ ์ •์˜ ํ›„, extends๋ฅผ ํ•ด์ค˜์•ผ ํ•œ๋‹ค.

4. import index

@api์™€ ๊ฐ™์ด directory๋ฅผ direct๋กœ alias ์ง€์ •ํ•  ๊ฒฝ์šฐ index๋ฅผ ๋ช…์‹œ์ ์œผ๋กœ import ํ•ด์ค˜์•ผ ํ•œ๋‹ค. (์ด ๋ถ€๋ถ„์€ ๊ฒ€ํ† ๊ฐ€ ๋” ํ•„์š”ํ•˜์ง€๋งŒ directory๋กœ ์ธ์‹ํ•˜์—ฌ index๋ฅผ ์•”๋ฌต์ ์œผ๋กœ importํ•  ์ˆ˜ ์—†๋Š” ๊ฒƒ์œผ๋กœ ์˜ˆ์ƒ๋œ๋‹ค.)

Tips

  • tsconfig๊ณผ webpack alias๋ฅผ ๋‘˜ ๋‹ค ์ง€์ •ํ•ด์ค˜์•ผ ํ•˜๋ฉฐ ์ด ๋ถ€๋ถ„ ํฌ๋งท์ด ๋‹ค๋ฆ„์— ์œ ์˜ํ•ด์•ผ ํ•œ๋‹ค.

JaeYeopHan avatar Aug 05 '19 04:08 JaeYeopHan