Next.js 使用指南--部署篇pm2

next

这样的配置默认 3000端口

 "scripts": {
    "dev": "next",
    "build": "next build",
    "start": "next start"
  },

报错

pm2 next start (function (exports, require, module, __filename, __dirname) { :: Created by npm, please don't edit manually.

cmd bug windos

用server.js解决 windows pm2 的bug

551  npm start
  552  pm2 start npm --name "my-next" -- run build
  553  pm2 ls
  554  pm2 logs
  555  pm2 ls
  556   pm2 start npm --name "my-nuxt" -- run start

errored 因为 windows pm2 的bug

用下面这个可以运行 完美

//server.js
// var cmd=require('node-cmd');
// cmd.run('npm start');

//or 
var exec = require('child_process').exec;
exec('npm run start', {windowsHide: true});
lenovo@lenovo-PC MINGW64 /e/jackieli/react-day-to-day/next
$ pm2 start server.js --name next -i 3
[PM2] Starting E:\jackieli\react-day-to-day\next\server.js in cluster_mode (3 instances)
[PM2] Done.
┌──────────┬────┬─────────┬─────────┬───────┬─────────┬─────────┬────────┬─────┬───────────┬────────┬──────────┐
│ App name │ id │ version │ mode    │ pid   │ status  │ restart │ uptime │ cpu │ mem       │ user   │ watching │
├──────────┼────┼─────────┼─────────┼───────┼─────────┼─────────┼────────┼─────┼───────────┼────────┼──────────┤
│ my-next  │ 0  │ N/A     │ fork    │ 0     │ errored │ 15      │ 0      │ 0%  │ 0 B       │ lenovo │ disabled │
│ my-nuxt  │ 1  │ N/A     │ fork    │ 0     │ errored │ 15      │ 0      │ 0%  │ 0 B       │ lenovo │ disabled │
│ next     │ 2  │ 1.0.0   │ cluster │ 17536 │ online  │ 0       │ 2s     │ 0%  │ 30.8 MB   │ lenovo │ disabled │
│ next     │ 3  │ 1.0.0   │ cluster │ 18016 │ online  │ 0       │ 1s     │ 0%  │ 30.7 MB   │ lenovo │ disabled │
│ next     │ 4  │ 1.0.0   │ cluster │ 18496 │ online  │ 0       │ 1s     │ 0%  │ 30.4 MB   │ lenovo │ disabled │
└──────────┴────┴─────────┴─────────┴───────┴─────────┴─────────┴────────┴─────┴───────────┴────────┴──────────┘
 Use `pm2 show <id|name>` to get more details about an app

改变端口

 "scripts": {
    "dev": "next -p 8088",
    "start": "next start -p 3033",
    "build": "next build"
  }
lenovo@lenovo-PC MINGW64 /e/jackieli/react-day-to-day/next
$ npm run dev

> next@1.0.0 dev E:\jackieli\react-day-to-day\next
> next -p 8088

[ wait ]  starting the development server ...
[ info ]  waiting on http://localhost:8088 ...

lenovo@lenovo-PC MINGW64 /e/jackieli/react-day-to-day/next
$ npm start

> next@1.0.0 start E:\jackieli\react-day-to-day\next
> next start -p 3033

> Ready on http://localhost:3033


set PORT=3001
Windows 系统在 cmd.exe 中运行 $ set PORT=1000

macOS & Linux 运行 $ PORT=1000

再运行 $ npm start 启动 RSSHub 即可将监听端口设置为 1000.

报错 没有a标签

function About() {
  return <div>about! <br/><Link href="/">
      go home
    </Link></div>;
}
utils.js:9 Warning: You're using a string directly inside <Link>. This usage has been deprecated. Please add an <a> tag as child of <Link>

要这样 用 
function About() {
  return <div>about! <br/><Link href="/">
      <a>go home</a>
    </Link></div>;
}

静态化

输入下面命令:

next build
next export
你可以在package.json添加一个 NPM 脚本,如下所示:

{
  "scripts": {
    "build": "next build",
    "export": "npm run build && next export"
  }
}
接着只用执行一次下面命令:

npm run export
然后你将会有一个静态页面应用在out 目录下。
 "export": "npm run build && next export"

serve静态服务器

lenovo@lenovo-PC MINGW64 /e/jackieli/react-day-to-day/next
$ serve out
UPDATE AVAILABLE The latest version of `serve` is 11.0.1
INFO: Accepting connections at http://localhost:5000


lenovo@lenovo-PC MINGW64 /e/jackieli/react-day-to-day/next

express koa 部署

lenovo@lenovo-PC MINGW64 /e/jackieli/react-day-to-day/next

$ NODE_ENV=production PORT=3034 node koa-server.js

Ready on http://localhost:3034

###报错 nodemon server.js

lenovo@lenovo-PC MINGW64 /e/jackieli/react-day-to-day/next
$ yarn add koa koa-router --save
yarn add v1.10.1
error An unexpected error occurred: "E:\\jackieli\\react-day-to-day\\next\\package.json: Unexpected token } in JSON at position 433".
info If you think this is a bug, please open a bug report with the information provided in "E:\\jackieli\\react-day-to-day\\next\\yarn-error.log".
info Visit https://yarnpkg.com/en/docs/cli/add for documentation about this command.

package.json 多了个 逗号 

lenovo@lenovo-PC MINGW64 /e/jackieli/react-day-to-day/next
$ nodemon server.js
[nodemon] 1.18.6
[nodemon] to restart at any time, enter `rs`
[nodemon] watching: *.*
[nodemon] starting `node server.js`
[nodemon] restarting due to changes...
[nodemon] restarting due to changes...
[nodemon] starting `node server.js`
没了用 

koa-server.js

//http版本

// const { createServer } = require('http');
// const next = require('next');
// const port = parseInt(process.env.PORT, 10) || 3000;
// const dev = process.env.NODE_ENV !== 'production';
// const app = next({ dev });
// const handler = app.getRequestHandler(app);
// app.prepare()
//   .then(() => {
//     createServer(handler)
//       .listen(port, (err) => {
//         if (err) throw err;
//         console.log(`> Ready on http://localhost:${port}`);
//       })
//   })



//koa版本


const Koa = require('koa')
const next = require('next')
const Router = require('koa-router')

const port = parseInt(process.env.PORT, 10) || 3000
const dev = process.env.NODE_ENV !== 'production'
const app = next({ dev })
const handle = app.getRequestHandler()

app.prepare().then(() => {
    const server = new Koa()
    const router = new Router()

    // router.get('/a', async ctx => {
    //   await app.render(ctx.req, ctx.res, '/b', ctx.query)
    //   ctx.respond = false
    // })

    // router.get('/b', async ctx => {
    //   await app.render(ctx.req, ctx.res, '/a', ctx.query)
    //   ctx.respond = false
    // })

    router.get('*', async ctx => {
      await handle(ctx.req, ctx.res)
      ctx.respond = false
    })

    server.use(async (ctx, next) => {
      ctx.res.statusCode = 200
      await next()
    })

    server.use(router.routes())
    server.listen(port, () => {
      console.log(`> Ready on http://localhost:${port}`)
    })
  }
)




//express 版本
// const express = require('express')
// const next = require('next')
// // const bodyParser = require('body-parser')
// // const compression = require('compression')
// const { join } = require('path')
// const { parse } = require('url')

// const dev = process.env.NODE_ENV !== 'production'
// const port = process.env.PORT || 3000
// const app = next({ dev })
// const handle = app.getRequestHandler()

// // const Redis = require('./services/redis')
// // const Auth = require('./services/auth')
// // const Routes = require('./services/routes')
// app.prepare().then(() => {
//   const server = express()

//   // server.use(bodyParser.json())
//   // server.use(bodyParser.urlencoded({ extended: false }))
//   // server.use(compression())

//   // Redis(server)
//   // Auth(server)
//   // Routes(server, app)

//   server.get('*', (req, res) => {
//     const parsedUrl = parse(req.url, true)
//     const { pathname } = parsedUrl

//     if (pathname === '/service-worker.js') {
//       const filePath = join(__dirname, '.next', pathname)

//       app.serveStatic(req, res, filePath)
//     } else {
//       handle(req, res, parsedUrl)
//     }
//   })

//   server.listen(port, err => {
//     if (err) throw err
//     console.log(`> Ready on http://localhost:${port}`)
//   })
// })

改变端口 静态化

"scripts": {
  "dev1": "next",
  "build1": "next build",
  "start1": "next start",
  "dev": "next -p 8088",
  "start": "next start -p 3033",
  "build": "next build",
  "export": "next export",
  "static-run": "npm run build && npm run export && serve out",
  "start-local": "NODE_ENV=production PORT=3034 node koa-server.js"
},

pm2 init ecosystem.config.js

module.exports = {
  apps : [
     {
      name: 'api-mock-online-apis-environment-development',
      script: 'server.js',
      instances: 1,
      autorestart: true,
      watch: true,
      max_memory_restart: '1G',
      restart_delay: 3000,
      append_env_to_name: true, //这表示会把当前环境的名字跟在我们进程的名字后面,最后当我们使用 npm run prd 部署完生产服务后,会发现我们生产服务的名字为 mydemo-production,当我们使用 npm run test 部署完测试服务后,会发现我们测试服务的名字为 mydemo-test,这样就可以让一个项目的生产环境和测试环境同时运行在一个服务器上了。
      // output: './logs/out.log',
      // error: './logs/error.log',
      // log: './logs/combined.outerr.log',
      // log_date_format: 'YYYY-MM-DD HH:mm Z',

      env: {
        NODE_ENV: 'development', //dev
        PORT: 3012
      },
      env_test: {
        NODE_ENV: 'test', //test
        PORT: 4012
      },
      env_stage: {
        NODE_ENV: 'stage', //qa
        PORT: 5012
      },
      env_production: {
        NODE_ENV: 'production', //prod
        PORT: 6012
      }
    },
    //开启下面注释的话 就是 注释掉上面的 append_env_to_name: true, 用reload 分别重启 或者script脚本

   //pm2 reload ecosystem.config.js --env development === pm2 start ecosystem.config.js
   // pm2 reload ecosystem.config.js --env test
   // pm2 reload ecosystem.config.js --env stage
   // pm2 reload ecosystem.config.js --env production

    // {
    //   name: 'next',
    //   script: 'koa-server.js',
    //   instances: 1,
    //   autorestart: true,
    //   watch: true,
    //   max_memory_restart: '1G',
    //   restart_delay: 3000,
    //   env_test: {
    //     NODE_ENV: 'test', //test
    //     PORT: 4012
    //   }
    // },
    //    {
    //   name: 'api-mock-online-apis-environment-stage',
    //   script: 'server.js',
    //   instances: 1,
    //   autorestart: true,
    //   watch: true,
    //   max_memory_restart: '1G',
    //   restart_delay: 3000,
    //   env_stage: {
    //     NODE_ENV: 'stage', //qa
    //     PORT: 5012
    //   }
    // },
    //  {
    //   name: 'api-mock-online-apis-environment-production',
    //   script: 'server.js',
    //   instances: 1,
    //   autorestart: true,
    //   watch: true,
    //   max_memory_restart: '1G',
    //   restart_delay: 3000,
    //   // env: {
    //   //   NODE_ENV: 'development', //dev
    //   //   PORT: 3012
    //   // },
    //   // env_test: {
    //   //   NODE_ENV: 'test', //test
    //   //   PORT: 4012
    //   // },
    //   // env_stage: {
    //   //   NODE_ENV: 'stage', //qa
    //   //   PORT: 5012
    //   // },
    //   env_production: {
    //     NODE_ENV: 'production', //prod
    //     PORT: 6012
    //   }
    // },
  ],

  // deploy : {
  //   production : {
  //     user : 'node',
  //     host : '212.83.163.1',
  //     ref  : 'origin/master',
  //     repo : 'git@github.com:repo.git',
  //     path : '/var/www/production',
  //     'post-deploy' : 'npm install && pm2 reload ecosystem.config.js --env production'
  //   }
  // }
};


原文地址:https://github.com/jackieli123723/jackieli123723.github.io/issues/77