Next.js(1) - Full-stack Framework of React - Creating Project
icon
password
Creating a ProjectMethod 1RunningMethod 2 Start by Sample CodeMethod 3 ManuallyCreate a folder and install dependenciesAdd scriptsCreate a directoryNext.js CLInext buildnext build --profilenext build --debugnext devnext startnext lintnext infoRoute
Creating a Project
Based on the latest version v14, Node.js 18.17 or later is required, supporting macOS, Windows, Linux systems.
Method 1
The fastest way to create a Next.js project is to use the
create-next-app
scaffold, you just need to run:After you finish the selection,
create-next-app
will automatically create project files and install dependencies. The directory and files of the created project are as follows:If you do not use
npx
, you can also use yarn
, pnpm
, bunx
:Running
Check the code of the
package.json
file in the project root directory:We can see that the script commands have
dev
, build
, start
, lint
, which correspond to development, build, run, code check.Use
npm run dev
for development. When deploying, first use npm run build
to build the production code, and then execute npm run start
to run the production project. Running npm run lint
will perform ESLint syntax check.npm run dev
The command line will prompt to run on port
3000
. We open the page http://localhost:3000/ in the browser, and if you see the following content, it means the project is successfully runningMethod 2 Start by Sample Code
Next.js provides a wealth of sample code, such as
with-redux
, api-routes-cors
, with-electron
, with-jest
, with-markdown
, with-material-ui
, with-mobx
. You can see from these names that these sample codes demonstrate various use cases of Next.js, such as how with-redux
demonstrates how Next.js is used with redux.You can visit github.com/vercel/next… to see what sample codes are available. If you want to use a specific sample code, like
with-redux
, you don't need to manually clone the code, you can create it directly when creating the project using the --example
parameter:Note: When using sample code, it will not prompt whether to use TypeScript, ESLint, etc. like when executing
npx create-next-app
, but will directly enter the project creation and dependency installation stage.Method 3 Manually
Create a folder and install dependencies
Now, create a folder, suppose named
next-app-manual
, cd
into this directory, and install the dependencies:npm will automatically create
package.json
and install dependencies.Add scripts
Open
package.json
, add the following content:Create a directory
Create a new
app
folder under next-app-manual
. Under app
, create layout.js
and page.js
files. The code is as follows:npm run dev
Next.js CLI
Through the code in
package.json
we know: when we run npm run dev
, what is actually executed is next dev
. The next
command comes from Next.js CLI. Next.js CLI can help you start, build and export projects.For the complete CLI command, you can execute
npx next -h
to view (-h
is the abbreviation of --help
).From the above figure, we can see that there are multiple commands that
next
can execute. We will introduce some of the most commonly used ones.Note: Because we created the project using
npx
, this method avoids the global installation of create-next-app
, so we do not have a next
command globally. If you want to execute the next
command, you can add a npx
before next
, just like the npx next -h
used this time.next build
Executing
next build
will create a production-optimized version of the project:The build output is as follows:
From the above figure, we can see that the build will output the information of each route, such as Size and First Load JS. Note that these values all refer to the size after gzip compression. Among them, First Load JS is represented in green, yellow, and red, where green indicates high performance, and yellow or red indicates the need for optimization.
Here we need to explain the meaning of Size and First Load JS. Normally, our developed Next.js project, its page performance is similar to a single-page application, that is, when the route jumps (we call it "navigation"), the page will not refresh, but will load the resources required by the target route and then display, so:
The total JS size required to load the target route = JS size required by each route + JS size individually dependent on the target route
Among them:
- The total JS size required to load the target route is
First Load JS
- The JS size that the target route depends on alone is
Size
- The JS size required by each route is the separately listed
First load JS shared by all
That is to say:
Take the route address
/
in the above figure as an example, 89 kB (First Load JS) = 5.16 kB (Size) + 83.9 kB (First load JS shared by all)The introduction in the official document is:
Size
: The size of the resources downloaded when navigating to this route. The size of each route only includes its own dependencies
First Load JS
: The size of the resources downloaded when loading this page
First load JS shared by all
: The JS size shared by all routes will be listed separately
Now we visit the production version of http://localhost:3000/:
The JS circled in red in the above figure is the JS that each page needs to load. According to the output of the command line, the total size is
83.9
kB, 413-dd2d1e77cac135ea.js
and page-9a9638f75b922b0c.js
are the individual JS of this page, with a total size of 5.16
kB, and all JS resources are 89 kB
. (Note: The number is not exactly the same as in the figure because gzip compression is not enabled)next build --profile
The command parameter is used to enable React's production performance analysis (requires Next.js v9.5 and above).
Then you can use React's
profiler
feature as in the development environment.Note: Here we execute the command npx next build --profile, not npm run build --profile. There are actually three ways to enable:
- Run
npx next build --profile
- First modify the
build
script command inpackage.json
to:Then runnpm run build
- Run
npm run build -- --profile
, addprofile
after theseparator,
profile
will be passed as a parameter to the actual executed command, the final command is stillnext build --profile
The use of the--debug
parameter in the next section is the same.
If you want to test this feature, first your browser needs to be equipped with React plugin, then you need to have a certain understanding of React's Profiler API (which is to measure the performance of component rendering). For example, now we change the code of
page.js
to:Execute
npm run dev
Usually, after executing
npm run build
and npm run start
, you open the console again, and you will find that performance measurement is not supported in the production environment:But if you execute
npx next build --profile
and then execute npm run start
, although the React plugin will show that it is currently in the production environment, the Profiler can be used:This feature can help everyone troubleshoot performance problems online.
next build --debug
This command parameter is used to enable more detailed build output:
Once enabled, it will output additional build information such as
rewrites
, redirects
, headers
.For example, let's modify the
next.config.js
file:Run
npx next build --debug
again, and the output is as follows:You can see that compared to the previous build output information, there are more
rewrites
, redirects
information. We will introduce the specific usage of rewrites and redirects in subsequent content.next dev
In development mode, running the program with
next dev
will automatically have hot loading, error reporting and other functions. By default, the program will start at http://localhost:3000
. If you want to change the port number:If you want to change the hostname (to allow access from other hosts):
next start
In production mode, run the program using
next start
. However, you need to execute next build
first to build the production code. When running, it is the same as the development mode, the program defaults to start at http://localhost:3000
. If you want to change the port number:next lint
Executing
next lint
will perform ESLint syntax checks for all files in the pages/
, app/
, components/
, lib/
, src/
directories. If you have not installed ESLint, this command will provide an installation guide. If you want to specify the directory to check:next info
next info
will print information related to the current system, which can be used to report bugs in the Next.js program. Execute in the root directory of the project:The print information is similar to:
This information can be posted to GitHub Issues for the Next.js official staff to troubleshoot.
Route
Next.js automatically sets up file system routing using the
pages
directory. This means that the way you arrange files and folders in the pages
directory directly sets up your app's routing. This makes routing simpler, as you can manage it through the file system without needing to write routes in the configuration file.Relationship between Files and Routes
- Basic Route:
pages/index.js
corresponds to the root route (/
).pages/about.js
will correspond to the/about
route.
- Nested Route: If you create a folder under the
pages
directory, the name of the folder will become part of the route. For example,pages/posts/first-post.js
will correspond to/posts/first-post
.
- Dynamic Route: The file (or folder) name surrounded by square brackets
[
and]
represents dynamic route parameters. For example,pages/posts/[id].js
can match any route like/posts/1
,/posts/abc
, whereid
can be obtained in the page through theuseRouter
hook of Next.js or thegetStaticProps
/getServerSideProps
function.
Underscore before Filename
In Next.js, files or folders that start with an underscore
_
have special meanings:_app.js
: This file is used to customize the default behavior of Next.js applications. You can use this file to maintain layout, maintain state, or add global styles. It is a top-level component shared by all pages.
_document.js
: Used to customize the structure of the HTML document. This file allows you to change the<html>
and<body>
tags of the document, usually used to add font links or static resource links. This file only runs on server-side rendering and is not applicable to client-side routing.
_error.js
: Used to customize error pages, such as 404 or 500 errors.
Examples
pages/index.js
→/
pages/about.js
→/about
pages/posts/first-post.js
→/posts/first-post
pages/posts/[id].js
→/posts/:id
(for example:/posts/123
)
pages/dashboard/settings.js
→/dashboard/settings
The benefit of using this file system routing is that you can intuitively organize your routing structure and easily create new routes without having to declare them in a centralized configuration file. This makes the management of routes simpler and more direct.
Last update: 2024-03-18
icon
password
I am currently in Melbourne
I am Looking for a Data Analytics Role…