preface

This article will introduce the construction of the environment of next. Js. Here we will take next+ KOA2 + Ant desin as an example to build the environment of full-stack development. Choose what works for you.

Good for: people who know Node.js, react, have heard about server-side rendering but haven’t put it into practice, know Next-js but don’t combine it with back-end frameworks and UI component libraries.

Tips: The author of this article is also a newbie. On the one hand, the purpose of writing this article is to strengthen my grasp of next, and on the other hand, I hope to help friends who really have such a need.

Build the next environment in a custom way

Create a project directory

  • mkdir next-learn
  • cd next-learn

If you are using Windows, you can download git and use git bash to run the above command, or create a next-learn folder on your desktop.

NPM/yarn initialization

I think you are familiar with NPM, but many of you have heard of YARN but haven’t. Here is a brief description: THE download speed of NPM is sometimes really uncomfortable. Yarn can greatly alleviate this situation, and in many cases, it is even faster than using Taobao image. Interested partners can go to the official website to learn about it and download it.

  • NPM initializes:npm init
  • Yarn initialization:yarn init

You can keep hitting enter, so I’m going to use YARN

Next, React, react-dom installation

This step is also introduced in detail on the website of next. Js

  • NPM installnpm install next react react-dom --save
  • Yarn installationyarn add next react react-dom

Change the package.json file

Package. json initialized with YARN init does not have a “scripts” field, because after yarn initialization, the package.json hollow object will be deleted. We can increase by ourselves

"scripts": {
  "dev": "next",
  "build": "next build",
  "start": "next start"
},
Copy the code

Next project run

  • Created in the project root directorypagesdirectory
  • Run the command line tool in the root directorynpm run devoryarn devOpen the project, the project is opened on port 3000 by default, then enter chromehttp:localhost:3000
  • We’re going to see 404 in the browser because we didn’t put anything in the Pages directory, okay

Create pages/index. Js

  • Create the index.js file in the Pages directory
export default() = ><h1>hello this is my first next.js page</h1>
Copy the code

The browser should be able to display the information we wrote

Use create-next-app scaffolding to set up the next environment

This approach is automated and does the same job as ours

  • Global installationnpm install -g create-next-app

Three ways to use create-next-app

  1. Install via NPXnpx create-next-app next-learn2(NPX is installed by default in node.js8 and later)
  2. Install using YARN Createyarn create next-app next-learn2(The way I use it)
  3. Install using create-next-appcreate-next-app next-learn

The difference between scaffolding and manual installation

  • Scaffolding is more automated and simpler
  • After the scaffolding tool is installed, there will be a components directory and a static directory that we installed manually. The Components directory has two components, and the static directory has a Favicon.ico that we can replace with our own project’s Favicon.ico

The rest is the same as we created manually. Open the project using YARN Dev to see what happens

Join koa2

Next. Js comes with its own server, but it can do very little except handle SSR rendering. We can use next.js as a middleware component for KOA, but of course you can also choose Express and egg.js, both of which are used similarly.

Installation of koa

  • NPM installnpm install koa --save
  • Yarn installationyarn add koa

Create server.js in the root directory

const Koa = require('koa')
const next = require('next')

constdev = process.env.NODE_ENV ! = ='production'
const app = next({ dev })
const handle = app.getRequestHandler()

app.prepare().then((a)= > {
  const server = new Koa()
  server.use(async (ctx, next) => {
    await handle(ctx.req, ctx.res)
    ctx.respond = false
  })

  server.listen(3000, () = > {console.log('server is running at http://localhost:3000')})})Copy the code

As for app.prepare(), we need to wait for all pages in the Pages directory to be compiled before starting koA. Handle (ctx.req, ctx.res) the req and res passed in here are the contents of the native HTTP module of NodeJS. If you are using Express or egg.js, note the arguments here

Change the package. The json

We will change the “dev” in the “scripts” field of package.json to “dev”: “node. /server.js”, because we are now going to start the KOA server and then type “yarn dev” or” NPM run dev” on the command line to start the service

Normal page access

You can then follow koA or some other Node.js framework for back-end development

Join the ant design

Set Next-js to parse the CSS properly

The default configuration of next.js does not parse CSS files, NPM install @zeit/next-css –saveyarn Install yarn add @zeit/next-css

Use in configuration files:

const WithCss = require('@zeit/next-css')

if(typeof require! = ='undefined') {
    require.extensions['.css'] = file= >{}}module.exports = WithCss({})
Copy the code

If you want to support sass, you can use WithSass(WithCss({}))

So if you want to do a CSS test, I’ve changed the color of the title

Install ANTd and babel-plugin-import

  • NPM installnpm install antd babel-plugin-import
  • Yarn installationyarn add antd babel-plugin-import

Add Babel configuration to create. Babelrc file in the root directory

{
    "presets": ["next/babel"]."plugins": [["import",
            {
                "libraryName": "antd"}}]]Copy the code

Add [“next/ Babel “] to enable Babel to support antD on demand in all Babel configuration plugins used in next

Introduce ANTD CSS files

Create the _app.js file in the Pages directory. This is where the App component from Next will be overwritten. Here we will not make changes to the App component, just import it and export it as is

import App from 'next/app'
import 'antd/dist/antd.css'

export default App
Copy the code

There is no CSS configuration in.babelrc because the use of the mini-CSs-extract-plugin is buggy

I tried to introduce a Button component in index.js and it displayed as expected successfully

import { Button } from 'antd'

......
<Button>Antd Button</Button>
......
Copy the code

conclusion

Ok, here is the next. Js + KOa + ANTD combination, if you are interested, you can try your favorite other combination

Write in the last

As a front-end intern, THE author does not know much. The problems or study notes encountered in previous study have always been stored in Evernote, which has not been published, but has saved hundreds of articles. Now I think I should share them while writing. Then I can only say awkwardly that what I have written is stored in evernote. I suggest that you can also share while learning in the future. Don’t hide everything like I did before.

In the follow-up, I will continue to update some feelings and study notes in study and life. At present, I still have some graduation projects, graduation thesis and work pressure, so the update may be slow