How can you convert Create React App (CRA) to next.js in 2024?
2 min readMay 22, 2024
Actually, you can just follow the article from Next.js official website to find the answer, but are they true? We need verify :)
I have one project repo with react for an appointment app: https://github.com/dotku/react-appointment-app
- Add Install the Next.js Dependency
```
npm install next@latest
``` - Create the Next.js Configuration File on root path
```
/** @type {import(‘next’).NextConfig} */
const nextConfig = {
output: ‘export’, // Outputs a Single-Page Application (SPA).
distDir: ‘./dist’, // Changes the build output directory to `./dist/`.
}
export default nextConfig
``` - Update TypeScript Configuration
```
{
“compilerOptions”: {
“target”: “es5”,
“lib”: [“dom”, “dom.iterable”, “esnext”],
“allowJs”: true,
“skipLibCheck”: true,
“strict”: false,
“forceConsistentCasingInFileNames”: true,
“noEmit”: true,
“esModuleInterop”: true,
“module”: “esnext”,
“moduleResolution”: “node”,
“resolveJsonModule”: true,
“isolatedModules”: true,
“jsx”: “preserve”,
“baseUrl”: “.”,
“incremental”: true,
“plugins”: [
{
“name”: “next”
}
],
“strictNullChecks”: true
},
“include”: [
“next-env.d.ts”,
“**/*.ts”,
“**/*.tsx”,
“.next/types/**/*.ts”,
“./dist/types/**/*.ts”
],
“exclude”: [“node_modules”]
}
``` - Create the Root Layout
It is getting tricky here, while react is usingsrc
as code directory, nextjs actually useapp
for the source code, we could keep both if you have large code is already using pure react for now, especially, nextjs doesn’t support redux store directly.
```
// file: app/layout.tsx
import type { Metadata } from ‘next’
export const metadata: Metadata = {
title: ‘React App’,
description: ‘Web site created with Next.js.’,
}
export default function RootLayout({
children,
}: {
children: React.ReactNode
}) {
return (
<html lang=”en”>
<body>
<div id=”root”>{children}</div>
</body>
</html>
)
}
``` - add styles
It is pretty common that we are using Tailwind CSS nowadays, so `postcss` andautoprefixer
package is required.
```
npm install postcss autoprefixer
```
and config file
```
module.exports = {
plugins: {
tailwindcss: {},
autoprefixer: {},
},
}
``` - Create the Entrypoint Page
Nextjs is using `page.tsx` instead `index.tsx` for entrypoint, aligns withlayout.tsx
. - Update Scripts in package.json
```
{
“scripts”: {
“dev”: “next dev”,
“build”: “next build”,
“start”: “next start”
}
}
```
```
#.gitignore
.next
next-env.d.ts
dist
``` - Start your program
so when you runnpm run dev
you should able to start your program.
I have full final version of Create React App (CRA) to next.js project over here: https://github.com/MTFundation/next-appointment-app.
Feel free to checkout and compare the change.