프레임워크/React(NextJs)
[React] typescript + webpack 에서 tsconfig.json - paths 속성 사용하기 (별칭 경로)
릴리코더
2022. 9. 10. 18:44
React를 webpack으로 직접 빌드하는 프로젝트와 typescript로 만든 경우
tsconfig.json에서 paths를 사용하기 위해서는 webpack에서 제공하는 플러그인 설정이 필요합니다.
경로를 잘못 설정하면 아래와 같은 에러가 발생하고,
Cannot find module '@pages/Main' or its corresponding type declarations.
플러그인을 설치하지 않으면, devServer모드나 build시 아래와 같은 에러가 발생합니다.
Module not found: Error: Can't resolve '@pages/Main' in 'C:/git/...'
설정 방법
프로젝트 구조
/src
// ...
/pages
// ...
App.tsx
index.tsx
tsconfig.json
webpack.config.js
tsconfig.json
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"@pages/*": ["src/pages/*"]
}
}
}
- baseUrl로 path의 시작지점을 지정합니다.
프로젝트 구조상 ./src 로 해도 되지만 저는 paths에 하나씩 적는걸 선호해서 위와 같이 작성했습니다.
- paths에 "별칭":["경로"]를 작성합니다.
마지막으로 tsconfig-paths-webpack-plugin 을 설치하고, webpack파일에 설정할 차례입니다.
$ npm i -D tsconfig-paths-webpack-plugin
webpack.config.js
const TsconfigPathsPlugin = require('tsconfig-paths-webpack-plugin');
module.exports = () => {
return {
// ...
resolve: {
// ...
plugins: [
new TsconfigPathsPlugin(),
],
// ...
}
// ...
}
}
설치한 모듈을 불러서, resolve의 plugins에 new TsconfigPathsPlugin으로 설정을 해줍니다.
App.tsx (설정한 별칭으로 파일에서 불러다 쓰는 방법)
import { BrowserRouter, Route, Routes } from 'react-router-dom';
import Main from '@pages/Main';
const App = () => {
return (
<>
<BrowserRouter>
<Header />
<Container>
<Routes>
<Route path="/" element={<Main />} />
</Routes>
</Container>
<Footer />
</BrowserRouter>
</>
);
};
export default App;
설정 완료 ! 🙌
eslint 설정에서 오류가 난다면 아래와 같은 규칙을 추가해주면 됩니다
{
"rules": {
"import/no-unresolved": "off"
}
}