Next. Js Scaffolding advanced series

  • Perfect for Ant-Design
  • Package fetch && add middleware
  • The deployment of online
  • Zeit Now deployed

Recently, people often asked me how to deploy the project in the first few articles about Next. Js, and some friends tried to use this scaffold to write the project, I am very happy and thank you, the writing is not good, I hope like-minded friends can give me more suggestions, so that I can improve ~. But would you beat me if I didn’t deploy either? Ha ha, don’t worry, today we will deploy online ~ to meet everyone’s needs, prove that this scaffold is very OK, can be used ~

Export Static Resources

The Next page is a static page without any data retrieval. The Next page is a static page without any data retrieval

The Export function is to Export the routing pages of the pages into static HTML files.

Export configuration

// package.json "scripts": { "start": "node server.js", "build": "next build", "prod": "NODE_ENV=production node server.js", // add export command "preexport": "next build", "export": "next export" } // next.config.js exportPathMap: async function (defaultPathMap) { return { '/': { page: '/' }, '/normal': { page: '/normal' }, '/edit': { page: '/edit' }, '/preview': { page: '/preview' } } }Copy the code

Serve to start

We use the export command to generate a static resource folder out for the project, as shown in the figure below:

In fact, this is very similar to the build folder generated by a normal SPA app such as create-react-app, which contains an index.html file. Similarly, we can use serve to boot ~

1. Install serve YARN add serve 2. Add startup commands "scripts": {"start": "node server.js", "build": "next build", "prod": "NODE_ENV=production node server.js", "preexport": "next build", "export": "next export", // add "static-run": "next export && serve out" } 3. Run the yarn static-run commandCopy the code

Run console screenshot, and access localhost:5000/

Deploy to Github Pages

Why introduce the previous step? My purpose is to deploy the static Next application as Github Pages to view the Demo. It is a waste of time not to use such a free and useful server.

The official documentation is very detailed, but also very clear, including each step of the why, I here for convenience, and then explain How I do it, or the application level ~ next-how-to deploy-github -Pages

Step 1: Set parameters related to export

See above

Step 2: Add the deploy command

// Deploy the following statement directly: "scripts": {"start": "node server.js", "build": "next build", "prod": "NODE_ENV=production node server.js", "preexport": "next build", "export": "next export", "static-run": "Next export && serve out", // add "deploy": "rm -rf node_modules/.cache && next build && next export && touch out/.nojekyll && git add out/ && git commit -m \"Deploy Next.js to gh-pages\" && git subtree push --prefix out origin gh-pages" },Copy the code

Step 3: Open a new local deploy-branch

So I’m going to tell you why we have a new local branch. Note that this branch does not need to be pushed to remote because the deploy operation is not suitable on the master and target GH-Pages branches for some special operations.

Here’s why:

  • Not suitable for master reasons

Because of routing, you need to configure the assetPrefix parameter before deploy. However, after configuring this parameter, you need to publish the parameter to Github Pages. As a result, the production environment will also carry the parameter, and many resources cannot be found. So it doesn’t fit in the master branch.

  • Not suitable for the GH-Pages branch

Github Pages relies on the GH-Pages branch, and the repository looks like this:

Obviously, if we put it on the GH-Pages branch, it would be a hassle every time (such as -f to commit, pull for remote repository and local code inconsistencies, etc.). In order to republish.

My solution is to create a new deploy-Branch local branch, name it whatever you want.

// next.config.js adds code const debug = process.env.node_env! == 'production'; Module. exports = {// set this to the name of your repository assetPrefix:! debug ? '/next-markdown-editor/' : '', ... }Copy the code

Step 4: Publish to Github Pages

// Run YARN deploy under deploy-branchCopy the code

[Note] : Do nothing, just run YARN deploy after adding assetPrefix. The result is shown below.

See the effect

Go to https://luffyzh.github.io/next-markdown-editor/, you can see, our Next project making Pages will release a success.

There is a problem

Problem Description: Error 404: error 404: Error 404: Error 404: Error 404: Error 404: Error 404 The reason from the home page of https://luffyzh.github.io/next-markdown-editor/ routing to jump to page1 is https://luffyzh.github.io/page1 by rendering, We are looking forward to should be https://luffyzh.github.io/next-markdown-editor/page1, so there were 404.

The solution

Babel-plugin-transform-define yarn add -d babel-plugin-transform-define # create env-config.js const prod = process.env.NODE_ENV === 'production'; module.exports = { 'process.env.BACKEND_URL': prod ? '/next-markdown-editor' : '' }; Babelrc ->.babelrc.js const envConfig = require("./env-config.js"); module.exports = { "presets": ["next/babel"], "plugins": [ ... // other plugin ["transform-define", <Link prefetch href='/normal'> <Button size='large' type='default'> </Link> // now <Link prefetch href='/normal' as={process.env.backend_URL + '/normal'}> <Button size='large' Type ='default'> normal editor </Button> </Link> # YARN deployCopy the code

Production Environment Deployment

I don’t think it’s necessary to talk about this… In fact, the authorities have made that very clear.

"Scripts ": {"start":" nodeserver.js ", // development environment command "build": "next build", // production environment package "prod": "NODE_ENV=production node server.js"Copy the code

Set NODE_ENV to production. In Windows, the command should be “prod”: “set NODE_ENV=production && node server.js”

PM2 advanced deployment takes effect

After reading the above, friends may sniff at 😄, but the truth is that the running code is the production code, but then to deploy may have some problems:

  • Monitor the status
  • The system crashes and cannot be restarted
  • Load balancing
  • . Other problems

To be clear, Next. Js is a Node-side framework (see startup commands for node Server). Therefore, I plan to use the more popular PM2 to deploy, THE specific use of PM2 I have talked about in a previous article, here is not more about, direct operation.

Portal: PM2 simple manual

  • Step 1: Configuration files
Module. exports = {apps: [{name: 'next-antd-scaffold', script: './server.js', CWD: './', // Current working path watch: ['.next' // Monitor changed directory, automatically restart once changed], ignore_watch: [// exclude 'node_modules', 'logs', 'static'], instances: Node_args: '--harmony', env: {NODE_ENV: 'development', PORT: 3006}, env_production: {NODE_ENV: 'development', PORT: 3006} 'production', PORT: 5000}, out_file: './logs/out.log', // Common log path error_file: './logs/err.log', // error log path merge_logs: True, log_date_format: 'YYYY-MM-DD HH: MM Z' // Set the date format of the log}]};Copy the code

Do not understand, it is good to look in the article in front ~ very simple.

  • Step 2: Deploy the service
$pm2 start php2.config. js --env productionCopy the code

As shown in the figure above, the development environment here is port 3006, and the production environment is port 5000. After using PM2 deployment service, access items are normal, including API service. Pm2 also provides logging and monitoring functions, as shown in the following figure:

All the consoles of the system output logs:All system error logs:

Wait, wait, wait…

PM2 also has many advanced features, everyone to explore it.

conclusion

This article is not hydrology lol. After all, it was written at the request of many friends. In the end, I think the scaffolding is almost finished. Can promote a wave ~ write a few projects to try

🌟Star or Fork, don’t get lost ~ next-antd-scaffold

communication

Interested in communication, we share discussion, join the group chat, if invalid please add QQ:439923999, note Next😄

QQ Group: 641113448 (Note: Next-js)