All Articles

next.js에서 절대경로 설정하기

package.json 파일에서
script 부분을

"scripts": {
    "dev": "NODE_PATH=. next dev",
    "build": "NODE_PATH=. next build",
    "start": "next start"
  }

이렇게 바꿔주기.
NODEPATH는 모듈 로드할 경우 모듈이 위치한 경로를 말하는데…
CRA 경우 모든 파일들이 src 디렉토리 내부에 존재하기 때문에 NODE
PATH=src로 설정해주면 모듈들 경로를 작성할 때
모듈이 위치한 디렉토리에 접근하기만 하면된다.

Next.js 경우에는 components 디렉토리, pages 디렉토리가 있는데 이 2개의 디렉토리를 내부에 두고 있는 부모 디렉토리가 없기 때문에 각각의 디렉토리에 접근해야 한다.
NODE_PATH=.로 설정해주면 모듈들 경로를 작성할 때 모듈이 위치한 디렉토리에 접근하기만 하면된다.

위에서 NODE_PATH를 설정해주기 전까지는 ./ 또는 ../ 같은 상대 경로를 사용하여 필요한 모듈이 위치해있는 곳까지 접근했어야 했다.

const withSass = require('@zeit/next-sass');
const withCSS = require('@zeit/next-css');

module.exports = withCSS(
  withSass({
    target: 'server',
    webpack(config, options) {
      config.module.rules.push(
        {
          test: /\.(png|jpg|gif|svg|eot|ttf|woff|woff2)$/,
          use: {
            loader: 'url-loader',
            options: {
              limit: 100000,
            },
          },
        },
        // (config.resolve.modules = [...config.resolve.modules, './src']),
      );
      return config;
    },
    =======================
    이 부분
    plugins: [
      'module-resolver',
      {
        alias: {
          '~/*': '.',
        },
      },
    ],
    ========================
  }),
);

기존 next.config.js에 위 코드에 나와있는 이 부분을 추가하면 된다.