Marais.lee
Welcome to Marais's IT Home
Marais.lee
전체 방문자
오늘
어제
  • 분류 전체보기 (87)
    • co-task 프로젝트 (7)
    • Study (28)
      • 자바스크립트 (5)
      • 모던 리액트 Deep Dive (7)
      • 용어 (1)
      • 컴퓨터과학 (2)
      • 코테 (12)
      • 네트워크 (0)
    • 개발 환경 (3)
    • Next.js (pages router) (9)
    • Next.js (app router + 14v) (4)
    • TypeScript (11)
    • 라이브러리 (8)
    • 후기 및 고민 (10)
    • 맥북관련 셋팅 및 오류 (4)
    • Obsidian | 옵시디언 (1)
반응형

인기 글

최근 글

블로그 메뉴

  • 홈
  • 태그
  • 방명록
250x250
hELLO · Designed By 정상우.
Marais.lee

Welcome to Marais's IT Home

ERROR | Module not found: Error: Can't resolve '@pages/UserListPage' in '.../src/routes' Webpack에러
개발 환경

ERROR | Module not found: Error: Can't resolve '@pages/UserListPage' in '.../src/routes' Webpack에러

2024. 7. 1. 23:48
728x90

상황

과제로 CRA없이 React, Typescript, Webpack 직접 설치 중

에러 직면

"Module not found: Error: Can't resolve '@pages/UserListPage' in '.../src/routes'"
위의 에러는 webpack의 번들링 과정중에서 일어난 에러로 tsconfig.json에 설정해 놓은 alias를 읽지 못해서 '@'를 사용했을 때 해당 경로 및 모듈을 이해하지 못하는 것이다.

해결 방안

(혹시 cra(create-react-app)를 사용했다면 'craco-alias'라고 구글링하면 쉽게 해결가능하다!)

/webpack.config.js
(...)
   resolve: {
        // 번들링을 할 파일 설정
        extensions: ['.js', '.jsx', '.ts', '.tsx'],
        alias: {
            '@src': path.resolve(__dirname, './src'), // 이 부분 필수, 아래는 폴더 구조에 맞춰서 추가
            '@assets': path.resolve(__dirname, './src/assets'),
            '@pages': path.resolve(__dirname, './src/pages'),
            '@components': path.resolve(__dirname, './src/components'),
            '@styles': path.resolve(__dirname, './src/styles'),
            '@utils': path.resolve(__dirname, './src/utils'),
            '@stores': path.resolve(__dirname, './src/stores'),
            '@api': path.resolve(__dirname, './src/api'),
        },
    },

추가 에러

하지만 "Cannot find module '@assets/logo.png' or its corresponding type declarations." 에러는 해결되지 않았다. 혹시 해당 경로 문제인가 싶어 테스트 파일을 만들어 보았는데, 잘 import 되는 것을 보니 png 문제인 것 같다.

해결!

1. src/assets 안에서 이미지를 가져오니 경로문제가 생겼다. 꼭 그 안에서 사용하지 않아도 되기 때문에 public/images 경로로 옮겨서 아래와 같이 직접 img 태그 안에 넣어주면 상대경로로 인식되기 때문에 잘 나온다. (위 사진의 import 삭제)

    <img src="/logo.png" alt="naraspace_logo" />

 

2. webpack.config.js의 이미지 경로 수정 해주기
production 모드에서도 잘 나올 수 있도록 경로를 수정해주었다.

./webpack.config.js
 (...)
  module: {
        // loader 설정 - 등록한 로더의 뒤의 요소부터 번들링에 반영
        // node_modules 제외
        rules: [
            {
                test: /\.(ts|tsx)?$/,
                use: ['esbuild-loader'],
                exclude: '/node_modules/',
            },
            {
                test: /\.css$/,
                use: [MiniCssExtractPlugin.loader, 'css-loader'],
            },
            {
                test: /\.(jpe?g|png|gif|svg)$/i,
                loader: 'file-loader',
                options: {
                    name: 'images/[contenthash].[ext]', // assets -> images로 수정
                },
            },
        ],
    },
728x90
반응형
저작자표시 비영리 변경금지 (새창열림)

'개발 환경' 카테고리의 다른 글

Eslint | react/react-in-jsx-scope off가 작동이 안되는 경우  (0) 2024.04.23
Eslint error 해결 방법 | 'extensions' has been removed, 'resolvepluginsrelativeto' has been removed.  (0) 2024.04.22
    '개발 환경' 카테고리의 다른 글
    • Eslint | react/react-in-jsx-scope off가 작동이 안되는 경우
    • Eslint error 해결 방법 | 'extensions' has been removed, 'resolvepluginsrelativeto' has been removed.
    Marais.lee
    Marais.lee
    구글링으로 한국어로 된 글을 찾지 못했거나 이해하는데 어려움이 있었던 이슈를 공유합니다.

    티스토리툴바