tip-archive
tip-archive copied to clipboard
Absolute path in VSCode with TypeScript, CRA, Jest (feat. craco)
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๋ฅผ ๋ ๋ค ์ง์ ํด์ค์ผ ํ๋ฉฐ ์ด ๋ถ๋ถ ํฌ๋งท์ด ๋ค๋ฆ์ ์ ์ํด์ผ ํ๋ค.