[Next.js] Next.js 설치
이번에 알아보면서 느낀건데, 내가 SSR과 CSR을 거의 잘못 알고 있었던 것 같다.
지금까지 생각하던 건 / 리액트 왜 쓰나 - SPA를 위해, 넥스트 왜 쓰나 - SSR을 위해, SSR은 왜 필요한가 - SEO 최적화 위해 / 였다. 그러면서 SPA는 SSR을 전제로 하고 있는 줄 알았다(위에 말이랑 약간 모순되긴 하지만 생각없이 외워서 그렇다). 그러나 그게 아니였고, 리액트는 CSR 위주로 돌아간다고 한다....!(대충격ㅎ) 그리고 넥스트는 리액트의 프레임워크, 즉 라이브러리의 프레임워크다. 넥스트는 첫 페이지를 백엔드에서 렌더링(프리렌더링)해서 SEO에 유리하게 만들어준다. 그리고 CSR을 부분적으로 사용하여 SSR의 단점인 페이지 전체를 받아와야하는 등의 단점을 보완했다고 한다.
https://nextjs.org/docs/getting-started
Getting Started | Next.js
Get started with Next.js in the official documentation, and learn more about all our features!
nextjs.org
https://github.com/vercel/next.js/
GitHub - vercel/next.js: The React Framework
The React Framework. Contribute to vercel/next.js development by creating an account on GitHub.
github.com
yarn create next-app
yarn 명령어로 next.js를 설치했다.
Next.js 레포지토리 살펴보기
create-next-app 이라는 그나마 익숙한..? 이름이 있어서 들어가보았다.
...
const program = new Commander.Command(packageJson.name)
.version(packageJson.version)
.arguments('<project-directory>')
.usage(`${chalk.green('<project-directory>')} [options]`)
.action((name) => {
projectPath = name
})
.option(
'--ts, --typescript',
`
Initialize as a TypeScript project.
`
)
.option(
'--use-npm',
`
Explicitly tell the CLI to bootstrap the app using npm
`
)
.option(
'--use-pnpm',
`
Explicitly tell the CLI to bootstrap the app using pnpm
`
)
.option(
'-e, --example [name]|[github-url]',
`
An example to bootstrap the app with. You can use an example name
from the official Next.js repo or a GitHub URL. The URL can use
any branch and/or subdirectory
`
)
.option(
'--example-path <path-to-example>',
`
In a rare case, your GitHub URL might contain a branch name with
a slash (e.g. bug/fix-1) and the path to the example (e.g. foo/bar).
In this case, you must specify the path to the example separately:
--example-path foo/bar
`
)
.allowUnknownOption()
.parse(process.argv)
async function run(): Promise<void> {
if (typeof projectPath === 'string') {
projectPath = projectPath.trim()
}
if (!projectPath) {
const res = await prompts({
type: 'text',
name: 'path',
message: 'What is your project named?',
initial: 'my-app',
validate: (name) => {
const validation = validateNpmName(path.basename(path.resolve(name)))
if (validation.valid) {
return true
}
return 'Invalid project name: ' + validation.problems![0]
},
})
if (typeof res.path === 'string') {
projectPath = res.path.trim()
}
}
if (!projectPath) {
console.log(
'\nPlease specify the project directory:\n' +
` ${chalk.cyan(program.name())} ${chalk.green(
'<project-directory>'
)}\n` +
'For example:\n' +
` ${chalk.cyan(program.name())} ${chalk.green('my-next-app')}\n\n` +
`Run ${chalk.cyan(`${program.name()} --help`)} to see all options.`
)
process.exit(1)
}
...
Next를 설치할 때 프로젝트 이름을 입력 받고 설치하는 등의 과정이 있는 듯
우연히..? 찾았는데 이게 맞나?...
#!/usr/bin/env node
import arg from 'next/dist/compiled/arg/index.js'
import { startServer } from '../server/lib/start-server'
import { getPort, printAndExit } from '../server/lib/utils'
import * as Log from '../build/output/log'
import isError from '../lib/is-error'
import { getProjectDir } from '../lib/get-project-dir'
import { cliCommand } from '../lib/commands'
const nextStart: cliCommand = (argv) => {
const validArgs: arg.Spec = {
// Types
'--help': Boolean,
'--port': Number,
'--hostname': String,
'--keepAliveTimeout': Number,
// Aliases
'-h': '--help',
'-p': '--port',
'-H': '--hostname',
}
let args: arg.Result<arg.Spec>
try {
args = arg(validArgs, { argv })
} catch (error) {
if (isError(error) && error.code === 'ARG_UNKNOWN_OPTION') {
return printAndExit(error.message, 1)
}
throw error
}
if (args['--help']) {
console.log(`
Description
Starts the application in production mode.
The application should be compiled with \`next build\` first.
Usage
$ next start <dir> -p <port>
<dir> represents the directory of the Next.js application.
If no directory is provided, the current directory will be used.
Options
--port, -p A port number on which to start the application
--hostname, -H Hostname on which to start the application (default: 0.0.0.0)
--keepAliveTimeout Max milliseconds to wait before closing inactive connections
--help, -h Displays this message
`)
process.exit(0)
}
const dir = getProjectDir(args._[0])
const host = args['--hostname'] || '0.0.0.0'
const port = getPort(args)
const keepAliveTimeoutArg: number | undefined = args['--keepAliveTimeout']
if (
typeof keepAliveTimeoutArg !== 'undefined' &&
(Number.isNaN(keepAliveTimeoutArg) ||
!Number.isFinite(keepAliveTimeoutArg) ||
keepAliveTimeoutArg < 0)
) {
printAndExit(
`Invalid --keepAliveTimeout, expected a non negative number but received "${keepAliveTimeoutArg}"`,
1
)
}
const keepAliveTimeout = keepAliveTimeoutArg
? Math.ceil(keepAliveTimeoutArg)
: undefined
startServer({
dir,
hostname: host,
port,
keepAliveTimeout,
})
.then(async (app) => {
const appUrl = `http://${app.hostname}:${app.port}`
Log.ready(`started server on ${host}:${app.port}, url: ${appUrl}`)
await app.prepare()
})
.catch((err) => {
console.error(err)
process.exit(1)
})
}
export { nextStart }
이게 yarn dev를 실행하면 나오는 부분인가??하다가
먼저 yarn start를 쳐보기로 했다.
바로 그 위치에서 yarn start를 치면 package.json을 찾을 수 없다고 나오는데, next를 설치한 후에 생성된 폴더로 들어가줘야 한다!
cd 폴더 이름
폴더 이름은 앞에 부분만 치고 탭 누르면 자동완성 된다~
yarn run v1.22.19
$ next start
ready - started server on 0.0.0.0:3000, url: http://localhost:3000
Error: Could not find a production build in the 'D:\hani\next\hani-01\.next' directory. Try building your app with 'next build' before starting the production server. https://nextjs.org/docs/messages/production-start-no-build-id
at NextNodeServer.getBuildId (D:\hani\next\hani-01\node_modules\next\dist\server\next-server.js:169:23)
at new Server (D:\hani\next\hani-01\node_modules\next\dist\server\base-server.js:58:29)
at new NextNodeServer (D:\hani\next\hani-01\node_modules\next\dist\server\next-server.js:70:9)
at NextServer.createServer (D:\hani\next\hani-01\node_modules\next\dist\server\next.js:140:16)
at async D:\hani\next\hani-01\node_modules\next\dist\server\next.js:149:31
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
바로 오류가 떴다.
build를 해서 .next 폴더를 만들어준 뒤에 실행해야 한다고 한다.
(오류창에 build를 찾을 수 없다고, build 후에 실행하라고 나와있다!)
yarn build
yarn start
pages>index.js
localhost:3000에 들어가면 나오는 첫 창~