next.js static html export (next export)

next.js에서 static site 만들기

next.js로 만든 코드를 static으로 추출하기위해서는 next export 명령어를 사용한다.

next export을 하면 nodejs 서버 없이 독립적으로 실행할 수 있는 정적 html(html, css, js) 파일로 내보낼 수 있다.

빌드 시점에 미리 page를 파악하고 이를 각각의 html 파일로 만들어내고 out폴더로 내보내진다.

동적 routes, nextjs 의 거의 모든 기능을 지원한다.

공식문서 참조 https://nextjs.org/docs/advanced-features/static-html-export

package.json의 script에 명령어를 셋팅해준다.

// package.json
"scripts": {
 "build": "next build && next export",
}

기본적으로 파일들은 /pages폴더 밑의 폴더와 파일들이 곧 페이지 경로가 되고 index는 폴더의 경로를 따르고, 다른 파일명은 경로를 만든다.

/index.html로 뽑아내려면 next.config.jsexportTrailingSlashtrue로 설정하면 된다.

//next.config.js
module.exports = {
    "exportTrailingSlash" : true,
};

ex)

pages/index.js => pages/index.html

pages/intro/index.js => pages/intro/index.html

pages/contact.js => pages/contact/index.html

pages/about/intro.js => pages/about/intro/index.html

주의할점

Automatic Static Optimization 이란?

위에 설명했던 것 처럼, 미리 빌드 타임에 정적 파일로 생성되서 CDN 등으로 캐싱되서 요청 시 사용되는 방식을 말한다. 이로 인해 요청 시마다 항상 정적 파일을 생성하지 않고, 미리 생성되어 캐싱된 파일만 바로 제공하면 되므로 굉장히 빠른 로딩이 가능하다.

Discussion and feedback