인프런 커뮤니티 질문&답변
Module not found: Error: Can't resolve './App' 에러
작성
·
871
0
안녕하세요. 강의에서 배운 내용 응용해서 사이드 프로젝트 만드는 중인데
Module not found: Error: Can't resolve './App' in '/Users/taetae/Documents/github/PicKIvy/frontend/src' 오류가 고쳐지지 않아 질문드립니다.
(시도해본 해결방법들)
[ Tsconfig.json ]
- “jsx": "react-jsx" 으로 설정됐는지 확인 -> 그래도 안됌 
- “paths" 확인 
> "baseUrl": "src", (원래 “.”이었음)
"paths": {
"@pages/*": ["pages/*"],
"@components/*": ["components/*"],
"@layouts/*": ["layouts/*"],
"@hooks/*": ["hooks/*"],
"@utils/*": ["utils/*"],
"@typings/*": ["typings/*"]
},
패스에 전부 src/붙여서 "@pages/*": [“src/pages/*"], 해봤는데 안됨
- “moduleResolution": "node", 확인 -> 그래도 안됌 
[ Web pack.config]
- Extensions: [ “.tsx”] 으로 설정됐는지 확인 -> 그래도 안됌 
- package-lock.json지우고 다시 Npm install 
안됌 ( rm -rf node_modules package-lock.json ->
npm cache clean --force -> npm install )
[ index.tsx ]
- import App from './App'; 을 import App from './App.tsx; ‘ 로 해봤는데 안됌 
[ 폴더구조, tsconfig ]

[ 웹팩 ]
import path from 'path';
import ReactRefreshWebpackPlugin from '@pmmmwh/react-refresh-webpack-plugin';
import webpack, { Configuration as WebpackConfiguration } from 'webpack';
import ForkTsCheckerWebpackPlugin from 'fork-ts-checker-webpack-plugin';
// import { BundleAnalyzerPlugin } from 'webpack-bundle-analyzer';
import { Configuration as WebpackDevServerConfiguration } from 'webpack-dev-server';
interface Configuration extends WebpackConfiguration {
  devServer?: WebpackDevServerConfiguration;
}
const isDevelopment = process.env.NODE_ENV !== 'production';
const config: Configuration = {
  name: 'PicKivy',
  mode: isDevelopment ? 'development' : 'production',
  devtool: isDevelopment ? 'inline-source-map' : 'hidden-source-map',
  resolve: {
    extensions: ['.js', '.jsx', '.ts', '.tsx', '.json'],
    alias: {
      '@hooks': path.resolve(__dirname, 'src/hooks'),
      '@components': path.resolve(__dirname, 'src/components'),
      '@layouts': path.resolve(__dirname, 'src/layouts'),
      '@pages': path.resolve(__dirname, 'src/pages'),
      '@utils': path.resolve(__dirname, 'src/utils'),
      '@typings': path.resolve(__dirname, 'src/typings'),
    },
  },
  entry: {
    app: './src/index.tsx',
  },
  target: ['web', 'es6'],
  module: {
    rules: [
      {
        test: /\.tsx?$/,
        loader: 'babel-loader',
        exclude: /node_modules/,
        options: {
          presets: [
            [
              '@babel/preset-env',
              {
                targets: { browsers: ['> 0.25%', 'not dead'] }, // 최신 브라우저 타겟팅
                debug: isDevelopment,
              },
            ],
            '@babel/preset-react',
            '@babel/preset-typescript',
          ],
          plugins: [
            '@babel/plugin-transform-runtime',
            isDevelopment && 'react-refresh/babel',
            '@emotion/babel-plugin',
          ].filter(Boolean),
        },
      },
      {
        test: /\.css$/,
        use: ['style-loader', 'css-loader'],
      },
      {
        test: /\.(png|jpg|gif|svg)$/,
        type: 'asset/resource',
      },
    ],
  },
  plugins: [
    new ForkTsCheckerWebpackPlugin({
      async: false,
    }),
    new webpack.EnvironmentPlugin({ NODE_ENV: isDevelopment ? 'development' : 'production' }),
  ],
  output: {
    path: path.join(__dirname, 'dist'),
    filename: '[name].[contenthash].js',
    publicPath: '/dist/',
  },
  devServer: {
    historyApiFallback: true,
    port: 3000,
    devMiddleware: { publicPath: '/dist/' },
    static: { directory: path.resolve(__dirname, 'public') },
    proxy: {
      '/api/': {
        target: 'http://localhost:3000',
        changeOrigin: true,
        ws: true,
      },
    },
  },
};
if (isDevelopment && config.plugins) {
  config.plugins.push(new webpack.HotModuleReplacementPlugin());
  config.plugins.push(
    new ReactRefreshWebpackPlugin({
      overlay: {
        useURLPolyfill: true,
      },
    }),
  );
//   config.plugins.push(new BundleAnalyzerPlugin({ analyzerMode: 'server', openAnalyzer: false }));
}
if (!isDevelopment && config.plugins) {
  config.plugins.push(new webpack.LoaderOptionsPlugin({ minimize: true }));
//   config.plugins.push(new BundleAnalyzerPlugin({ analyzerMode: 'static' }));
}
export default config;
 코드 복붙하니까 코드가 이상하게 나와서 캡쳐본도 올립니다. (test: /\.tsx? 아래부분부터)
코드 복붙하니까 코드가 이상하게 나와서 캡쳐본도 올립니다. (test: /\.tsx? 아래부분부터)
[ App, index ]
 @page 하니까 에러떠서 ./로 했습니다.
@page 하니까 에러떠서 ./로 했습니다.
이것때문에 계속 못하고 있는데 저에게 답을 알려주시면 감사하겠습니다...ㅠ.ㅜ
답변 1
0

지금보니까 pages/WelcomePage에서도 에러가 나네요. src 폴더 존재때문에 설정에서 뭔가 안 맞는 것 같은데 잘 안보입니다. src 폴더 없으면 잘 되나요??
프론트엔드 src폴더를 삭제하고 다시 src 폴더를 만들어서 파일 넣어줬더니 정상 작동됐습니다!
( 아직 해결되지 않은 것 )
- 코드는 동일한데 왜 폴더를 삭제하고 다시 만드니까 작동할까요? 캐시 문제였을까요? 
- @ 사용 못함 
src/ 혹은 ./로 경로를 설정하면 에러가 나지 않는데 @을 사용하면 에러가 납니다.
( 에러 없는 경우 )


(에러 생기는 경우)
tsconfig 파일
"baseUrl": "./src",
"paths": { "@layouts/*": ["layouts/*"],}
},
"include": ["**/*"]
---------------------------------------
App index
import WelcomePage from '@pages/WelcomePage';
저도 @써보고 싶은데 왜 안되는 걸까요..!ㅠㅠ





npm start하면 첫 페이지에 뜨는 에러입니다.
(에러메세지)
ERROR in ./src/App.tsx 5:0-41
Module not found: Error: Can't resolve '@pages/HousePage' in '/Users/taetae/Documents/github/PicKIvy/frontend/src'
ERROR in ./src/App.tsx 6:0-37
Module not found: Error: Can't resolve '@pages/JoinPage' in '/Users/taetae/Documents/github/PicKIvy/frontend/src'
ERROR in ./src/pages/WelcomePage/index.tsx 8:0-50
Module not found: Error: Can't resolve '@layouts/commonStyle' in '/Users/taetae/Documents/github/PicKIvy/frontend/src/pages/WelcomePage'
(다른 시도)
@를 쓴게 문제인가?싶었는데 다른 인덱스파일은 괜찮은데 app에서만 에러가 납니다.
그리고 이해가 안가는 점은
제가 웰컴페이지만 경로를 바꿔봤는데 웰컴은 에러가 사라졌고, 하우스&사인업은 에러가 그대로였습니다. 그래서 하우스도 ./ 이렇게 경로를 바꿨더니 하우스파일에서 임포트하는 모든 경로가 에러로 떴습니다ㅠ 대체 뭔지 모르겠습니다..
제가 저 파일들 개인 깃허브에 올렸는데 혹시 깃허브 주소 알려드려도 될까요?