우선 webpack.config.js
에
devServer: {
port: 3000,
historyApiFallback: true // this!
},
를 추가해준다. 하지않을경우 webpack-dev-server
는 /
로 올 경우는 index.html
을 로드하지만 예를 들어 /post
를 요청할경우 해당 위치에 있는 리소스를 로드하려고 한다.
historyApiFallback
을 추가하면 404에러가 발생할 때 index.html
을 로드한다.
하지만 현재 상태로는 webpack-dev-server
는 nested route를 지원하지 않는다. 즉, localhost:3000/post
은 동작하지만 localhost:3000/post/answer
는 동작하지 않는다.
localhost:3000/post/answer
를 입력하면 localhost:3000/post/answer/index.js
를 찾으려고 하거나 404 Error
가 발생한다. 이를 해결하기 위해 stackoverflow를 찾다보니 여러가지 해결방법이 나왔다.
webpack.config.js
의 output
에 publicPath: '/'
를 추가하는 것index.js
를 import하는 index.html
에서 import하는 방식을 src='index.js'
에서 src='/index.js'
로 바꾸는 것이었다. 이 중 나는 1번 해결방법은 동작하지 않았고 2번으로 해결했다.
AS-IS
<html>
<head>
<title>JS Choi</title>
</head>
<body>
<div id="root"></div>
<script src="index.js"></script>
</body>
</html>
TO-BE
<html>
<head>
<title>JS Choi</title>
</head>
<body>
<div id="root"></div>
<script src="/index.js"></script>
</body>
</html>
이렇게 바꾸어주면 주소창의 경로가 아니라 항상 root(/
)에서 index.js
를 탐색하기때문에 원하는 결과가 나온다.