如何运行Next Js应用程序构建(出)目录?

问题描述 投票:0回答:4

我已经完成了 Next Js 应用程序的开发,到目前为止我已经使用 vercel

完成了自动部署

到目前为止一切都很好..但是我需要构建 Next Js 应用程序并与团队共享构建文件夹以便在服务器中部署。

我遵循的命令,

npm run build
&
npm run export

上面创建了

out
目录。那么如何在我的本地计算机中运行这个 out 目录,以在与团队共享之前检查构建文件夹是否按预期工作?

out
目录的文件夹结构:

 -> out

      -> _next
             -> static
             -> xxxxxxxxxxxxx (some random name)
      -> static
      -> home.png
      -> location.png

所以任何人都可以帮助我如何运行这个生成的构建文件夹(out)来检查开发的 Next Js 应用程序是否在我的本地计算机中正常工作,然后我可以将相同的构建文件夹共享给团队?

具体来说,我想知道如何在本地构建下一个 js 应用程序,然后测试本地构建的文件夹,该文件夹将运行该应用程序并可以将工作构建共享给团队中的任何人。

在这里提出问题https://github.com/vercel/next.js/discussions/16439但这无论如何都没有帮助..

reactjs npm deployment next.js server-side-rendering
4个回答
10
投票

官方的 Next 静态导出示例使用 serve 来“服务”

out
目录。由于
out
目录只是一堆静态文件,因此您需要某种与外部世界/内部网络的连接层。您可以使用 nginx 之类的东西来服务这些资产(这样就无需运行两个 Web 服务器)。但是,如果您正在寻找一种简单的方法来运行本地 staging 构建,那么您需要使用某种 Web 服务器:expresshttp-serverserve 等.

...并且可以将工作版本分享给团队中的任何人。

如果您处于远程位置并连接到 WAN,那么您团队中的任何人都可以访问暂存版本(例如:

http://wanlocalip:3000
- 您可以使用 address 打印出 console message)。如果您连接到 WAN 并且没有自己的服务器,那么您必须使用第三方服务(例如 vercel、AWS 或 Digital Ocean 等)创建远程临时环境.


既然如此,让我们采用官方的 with-static-export 示例并设置一个自定义的 Express 服务器。

首先,我们将添加一些依赖项:

yarn add chalk dotenv express

package.json
文件脚本调整为:

  "scripts": {
    "dev": "next",
    "export": "next build && next export",
    "start": "NODE_ENV=production node ./server.js"
  },

然后我们会在根目录下创建一个

server.js
文件:

服务器.js

const dotenv = require("dotenv");
// import ENVs from ".env.local" and append to process
dotenv.config({ path: ".env.local" }); 
const express = require("express");
const address = require("address");
const chalk = require("chalk");

// create express web server instance
const app = express();
// pull out ENVs from process
const { LOCALHOST, PORT } = process.env;
// get the Local IP address
const LOCALIP = address.ip();

// tell express to serve up production assets from the out directory
app.use(express.static("out"));

// tell express to listen for incoming connections on the specified PORT
app.listen(PORT, (err) => {
  if (!err) {
    // log the LOCALHOST and LOCALIP addresses where the app is running
    console.log(
      `\n${chalk.rgb(7, 54, 66).bgRgb(38, 139, 210)(" I ")} ${chalk.blue(
        "Application is running at"
      )} ${chalk.rgb(235, 220, 52).bold(LOCALHOST)} ${chalk.blue(
        "or"
      )} ${chalk.rgb(235, 220, 52).bold(`http://${LOCALIP}:${PORT}`)}\n`
    );
  } else {
    console.err(`\nUnable to start server: ${err}`);
  }
});

可选我们可以调整

next.config.js
以在开发中显示compilation message

next.config.js

const { DefinePlugin } = require("webpack");
const FriendlyErrorsWebpackPlugin = require("friendly-errors-webpack-plugin");
const address = require("address");

const { LOCALHOST, NODE_ENV, PORT } = process.env;
const LOCALIP = address.ip();

const plugins = (isServer) => {
  const plugins = [];

  if (!isServer) {
    plugins.push(
      /* OPTIONAL -- append ENVS to client-side process */
      new DefinePlugin({
        "process.env": {
          LOCALHOST: JSON.stringify(LOCALHOST),
          NODE_ENV: JSON.stringify(NODE_ENV),
        },
      })
    );
  } else {
    plugins.push(
     /* add console compilation messages */
      NODE_ENV === "development" &&
        new FriendlyErrorsWebpackPlugin({
          compilationSuccessInfo: {
            messages: [
              `Local development build: \x1b[1m${LOCALHOST}\x1b[0m`,
              LOCALIP &&
                `Remote development build: \x1b[1mhttp://${LOCALIP}:${PORT}\x1b[0m`,
            ].filter(Boolean),
            notes: [
              "Note that the development build is not optimized.",
              "To create a production build, use \x1b[1m\x1b[32myarn export\x1b[0m.\n",
            ],
          },
          clearConsole: false,
        })
    );
  }

  return plugins.filter(Boolean);
};

module.exports = {
  webpack(config, { isServer }) {
    /* adds custom plugins to client and/or server */
    config.plugins.push(...plugins(isServer));

    /* return new config to next */
    return config;
  },
};

现在我们已经完成了所有设置,我们可以运行

yarn export
来构建项目并将其导出到
out
目录,然后我们可以通过运行
yarn start
来运行本地暂存环境。访问 console 中打印的地址之一。

本地

WAN(仅适用于连接到 WAN 内 LAN 连接的用户)


单击此处查看上述内容的工作存储库示例。

如果您的项目仍然遇到问题,请共享存储库;否则很难帮你解决问题。


5
投票

运行此命令:

npm run build && npm run export

它将创建一个 out 目录。

然后

要运行

out/build/dist
目录,您可以安装
web server for chrome addon in your chrome browser
或安装
http-server
。我在这里覆盖
web server addon

chrome 网络服务器链接: https://chrome.google.com/webstore/detail/web-server-for-chrome/ofhbbkphhbklhfoeikjpcbhemlocgigb?hl=en

启动应用程序,然后选择您的

out/build/dist
文件夹,然后它将为您提供一个链接,只需导航到给定的链接即可。

如果您想更改

out
目录名称,请参阅下文

next.js 创建

.next
目录而不是
build

要创建自定义目录,例如

build
,您需要在
next.config.js

中设置配置

next.config.js

module.exports = {
  distDir: 'build',
}

3
投票

如果您的 NextJS 站点包含嵌套路径文件夹/文件,则需要配置有后备逻辑的本地服务器。考虑一个

next export
,它会生成:

/out
  /_next
  /docs
    /guide.html
  /index.html
  /docs.html

当您加载网址

http://localhost:3000/docs
时,您的本地服务器应该提供
/docs.html
服务,因为
/docs/index.html
不存在。

默认情况下唯一正确配置的本地服务器是: https://www.npmjs.com/package/serve

npm install serve --save-dev

然后将

dev:static
命令添加到 package.json 中:

  "scripts": {
    "dev": "next dev",
    "dev:static": "serve ./out",
    "build": "next build && next export",
    "start": "next start"
  },

然后运行命令在本地查看静态站点:

npm run build
npm run dev:static

0
投票

自从 App Router 来到这里的任何人都需要通过将以下内容添加到其

out/
文件中来配置下一步到
next.config
目录的输出。

/**
 * @type {import('next').NextConfig}
 */
const nextConfig = {
  output: 'export',
 
  // Optional: Change links `/me` -> `/me/` and emit `/me.html` -> `/me/index.html`
  // trailingSlash: true,
 
  // Optional: Prevent automatic `/me` -> `/me/`, instead preserve `href`
  // skipTrailingSlashRedirect: true,
 
  // Optional: Change the output directory `out` -> `dist`
  // distDir: 'dist',
}
 
module.exports = nextConfig

这里是文档

© www.soinside.com 2019 - 2024. All rights reserved.