• 카테고리

    질문 & 답변
  • 세부 분야

    프론트엔드

  • 해결 여부

    미해결

react-router-dom@6 nested route

22.08.26 07:29 작성 조회수 730

0

안녕하세요.

"react-router-dom": "^6.3.0" 쓰고 있습니다.
 
layouts/App/index.tsx에서 login의 경우
<Route path="/login" element={<LogIn />} /> 로 하면 브라우저에서 http://localhost:3090/login로 들어가면 화면이 잘 뜨는데, 
 
<Route path="/login/hi" element={<LogIn />} />로 하면 브라우저에서
http://localhost:3090/login/hi로 들어가면 화면이 안보입니다. 왜 path에 /를 두개 이상 넣으면 안될까요?
 
 
또한, https://www.inflearn.com/questions/417079
이분과 똑같이 해도 
localhost:3090/workspace/dm 으로 들어가면 404 에러가 나오고 브라우저에서 흰페이지만 로딩 됩니다. 
 
https://reactrouter.com/en/v6.3.0/getting-started/tutorial
 
여기의 nested routes부분을 따라서 Outlet과 링크를 이용해서 똑같이 해봐도
링크를 누르면 localhost:3090/dm 으로 가지고, localhost:3090/workspace/dm으로 안가집니다.. 
 
 
그래서 layouts/workspace/index.tsx에서
Link의 to="/dm"을 to="/workspace/dm"으로 바꾸고
 
 
localhost:3039/workspace 에서 dm 링크를 누르면 localhost:3039/workspace/dm로 가져서 잘 로딩되긴 하는데..
 
 
리프레쉬 버튼을 누르면 다시 흰페이지만 나오고 404 에러뜹니다.. 
 
 
 
 
login 라우터도 /login은 되지만 /login/hi 이런식으로 /를 두개이상 붙이면 작동이 안되는데.. 제가 애초에 처음부터 세팅을 잘못한 걸까요..? ㅠ
 
 
 
 
package.json 입니다
{
"name": "slact-front",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"dev": "TS_NODE_PROJECT=\"tsconfig-for-webpack-config.json\" webpack serve --env development",
"build": "TS_NODE_PROJECT=\"tsconfig-for-webpack-config.json\" NODE_ENV=production webpack",
"lint": "eslint . --ext ts,tsx"
},
"author": "",
"license": "MIT",
"dependencies": {
"@emotion/babel-plugin": "^11.1.2",
"@emotion/react": "^11.0.0",
"@emotion/styled": "^11.0.0",
"@jjordy/swr-devtools": "^2.0.7",
"@loadable/component": "^5.14.1",
"@types/autosize": "^4.0.0",
"@types/gravatar": "^1.8.3",
"@types/loadable__component": "^5.13.1",
"@types/react": "^17.0.0",
"@types/react-dom": "^17.0.0",
"@types/react-mentions": "^4.1.0",
"@types/react-router-dom": "^5.3.3",
"autosize": "^5.0.1",
"axios": "^0.21.4",
"core-js": "^3.14.0",
"dayjs": "^1.10.4",
"gravatar": "^1.8.2",
"react": "^17.0.1",
"react-custom-scrollbars-2": "^4.3.0",
"react-dom": "^17.0.1",
"react-mentions": "^4.1.1",
"react-router": "^6.3.0",
"react-router-dom": "^6.3.0",
"react-toastify": "^8.0.2",
"regexify-string": "^1.0.5",
"socket.io-client": "^4.2.0",
"swr": "^1.0.1",
"typescript": "^4.4.2"
},
"devDependencies": {
"@babel/core": "^7.12.10",
"@babel/preset-env": "^7.12.11",
"@babel/preset-react": "^7.12.10",
"@babel/preset-typescript": "^7.12.7",
"@pmmmwh/react-refresh-webpack-plugin": "^0.5.0-beta.4",
"@types/fork-ts-checker-webpack-plugin": "^0.4.5",
"@types/node": "^14.14.22",
"@types/react-router": "^5.1.18",
"@types/webpack": "^5.28.0",
"@types/webpack-bundle-analyzer": "^4.4.0",
"@types/webpack-dev-server": "^4.0.3",
"@typescript-eslint/eslint-plugin": "^5.34.0",
"@typescript-eslint/parser": "^5.34.0",
"babel-loader": "^8.2.2",
"css-loader": "^6.2.0",
"eslint": "^7.18.0",
"eslint-config-prettier": "^8.3.0",
"eslint-plugin-prettier": "^4.0.0",
"eslint-plugin-react": "^7.30.1",
"eslint-plugin-react-hooks": "^4.2.0",
"fork-ts-checker-webpack-plugin": "^6.1.0",
"prettier": "^2.2.1",
"react-refresh": "^0.10.0",
"style-loader": "^3.2.1",
"ts-node": "^10.2.1",
"tsconfig-paths": "^3.9.0",
"webpack": "^5.36.2",
"webpack-bundle-analyzer": "^4.4.0",
"webpack-cli": "^4.10.0",
"webpack-dev-server": "^4.0.0"
}
}

답변 2

·

답변을 작성해보세요.

1

일단 중첩 라우트 시에는 /workspace/*로 뒤에 *를 붙이셔야 할 것 같습니다. wepback dev에서 historyApiFallback을 on하셔야 새로고침 시에도 나옵니다.

0

hyunnnn님의 프로필

hyunnnn

2022.08.27

답변 감사합니다.

webpack.config.ts 파일에서

devServer: {
    historyApiFallback: true,

historyApiFallback 설정 트루로 되어있어요.

path="/signup"로 하면 나오던 signup 컴포넌트가 path="/signup/form" 으로 바꿔서 슬래쉬 하나 더 쓰면 SignUp 컴포넌트도 안보이네요..

image

image

터미널을 보니까 에러가 떳더라구요..

image

Error parsing bundle asset 해결하려고 구글해봤는데 옳은 방법인지는 모르겠지만.. 아래 코맨드를 터미널에 쳐봤습니다.

webpack --profile --json > stats.json && webpack-bundle-analyzer stats.json dist/

image

이런 에러가 뜹니다..

아래는 제 webpack.config.ts 파일입니다.

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: 'slact-front',
  mode: isDevelopment ? 'development' : 'production',
  devtool: !isDevelopment ? 'hidden-source-map' : 'inline-source-map',
  resolve: {
    extensions: ['.js', '.jsx', '.ts', '.tsx', '.json'],
    alias: {
      '@hooks': path.resolve(__dirname, 'hooks'),
      '@components': path.resolve(__dirname, 'components'),
      '@layouts': path.resolve(__dirname, 'layouts'),
      '@pages': path.resolve(__dirname, 'pages'),
      '@utils': path.resolve(__dirname, 'utils'),
      '@typings': path.resolve(__dirname, 'typings'),
    },
  },
  entry: {
    app: './client',
  },
  target: ['web', 'es5'],
  module: {
    rules: [
      {
        test: /\.tsx?$/,
        loader: 'babel-loader',
        options: {
          presets: [
            [
              '@babel/preset-env',
              {
                targets: { browsers: ['IE 10'] },
                debug: isDevelopment,
              },
            ],
            '@babel/preset-react',
            '@babel/preset-typescript',
          ],
          env: {
            development: {
              plugins: [
                ['@emotion/babel-plugin', { sourceMap: true }],
                require.resolve('react-refresh/babel'),
              ],
            },
            production: {
              plugins: ['@emotion/babel-plugin'],
            },
          },
        },
      },
      {
        test: /\.css?$/,
        use: ['style-loader', 'css-loader'],
      },
    ],
  },
  plugins: [
    new ForkTsCheckerWebpackPlugin({
      async: false,
      // eslint: {
      //   files: "./src/**/*",
      // },
    }),
    new webpack.EnvironmentPlugin({
      NODE_ENV: isDevelopment ? 'development' : 'production',
    }),
  ],
  output: {
    path: path.join(__dirname, 'dist'),
    filename: '[name].js',
    publicPath: '/dist/',
  },
  devServer: {
    historyApiFallback: true,
    port: 3090,
    devMiddleware: { publicPath: '/dist/' },
    static: { directory: path.resolve(__dirname) },
    hot: true,
    proxy: {
      '/api/': {
        target: 'http://localhost:3095',
        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;

아, 저건 app.js 경로문제입니다. index.html에서 /dist/app.js 하셔야합니다 ./dist/app.js 대신에요.

다른 웹팩 설정은 아예 건들지 마세요.

hyunnnn님의 프로필

hyunnnn

2022.08.30

감사합니다!!