如何使用自定义服务器构建 next.js 应用程序以在 Typescript 中进行生产

JBa*_*zuk 3 typescript next.js

我有一个自定义的 Express 服务器,用于创建 api 并托管 next.js 生成的静态内容。当我尝试构建生产时,它说:

Error: Could not find a production build in the 'path/to/project/.next' directory. Try building your app with 'next build' before starting the production server.

JBa*_*zuk 9

next.js 项目和自定义服务器必须单独构建。

  1. 删除任意.next和dist文件夹
  2. 在项目根目录中,创建一个名为 的附加 tsconfig 文件 tsconfig.server.json,该文件扩展了主tsconfig.json 配置。假设自定义服务器位于一个文件夹中./server,并且开发人员希望调用输出目录./dist。
{
  "extends": "./tsconfig.json",
  "compilerOptions": {
    "module": "commonjs",
    "outDir": "dist",
    "target": "es2017",
    "isolatedModules": false,
    "noEmit": false
  },
  "include": ["server"]
}
Run Code Online (Sandbox Code Playgroud)
  1. 编辑脚本于package.json
"scripts": {
    "build:server": "tsc --project tsconfig.server.json",
    "build:next": "next build",
    "build": "npm run build:next && npm run build:server",
    "start:prod": "NODE_ENV=production node dist/server/index.js",
    ...
}
Run Code Online (Sandbox Code Playgroud)