如何运行 Next Js 应用程序构建(输出)目录? [英] How to run Next Js application build (out) directory?

查看:130
本文介绍了如何运行 Next Js 应用程序构建(输出)目录?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

我遵循的命令,

npm run build &npm 运行导出

上面创建了 out 目录.那么如何在我的本地机器上运行这个 out 目录来检查构建文件夹是否按预期工作,然后再与团队共享?

out目录的文件夹结构:

 ->出去->_下一个->静止的->xxxxxxxxxxxxx(一些随机名称)->静止的->主页.png->位置.png

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

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

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

解决方案

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

<块引用>

...并且可以将工作构建分享给团队中的任何人.

如果您在远程并连接到 WAN,那么您团队中的任何人都可以访问暂存构建(例如:http://wanlocalip:3000 - 您可以使用 地址打印出控制台消息).如果您没有连接到 WAN 并且没有自己的服务器,那么您必须使用第三方服务(如 vercel、AWS 或 Digital)创建远程登台环境海洋等等.


除此之外,让我们采取官方的 with-static-export 示例并设置自定义快递服务器.

首先,我们将添加一些依赖项:yarn add chalk dotenv express

package.json文件脚本调整为:

 脚本":{开发":下一个",导出":下一个构建 &&下一个出口",开始":NODE_ENV=生产节点./server.js"},

然后我们会在根目录下创建一个server.js文件:

server.js

const dotenv = require("dotenv");//从.env.local"导入 ENV并附加到进程dotenv.config({ path: ".env.local" });const express = require("express");常量地址 = 要求(地址");const chalk = 要求(粉笔");//创建快速网络服务器实例常量应用程序 = 快递();//从进程中拉出 ENV常量 { 本地主机,端口 } = process.env;//获取本地IP地址常量 LOCALIP = 地址.ip();//告诉 express 从 out 目录提供生产资源app.use(express.static(out"));//告诉 express 监听指定 PORT 上的传入连接app.listen(PORT, (err) => {如果(!错误){//记录应用程序运行的 LOCALHOST 和 LOCALIP 地址控制台日志(`
${chalk.rgb(7, 54, 66).bgRgb(38, 139, 210)("I")} ${chalk.blue(应用程序正在运行")} ${chalk.rgb(235, 220, 52).bold(LOCALHOST)} ${chalk.blue(或")} ${chalk.rgb(235, 220, 52).bold(`http://${LOCALIP}:${PORT}`)}
`);} 别的 {console.err(`
无法启动服务器:${err}`);}});

可选我们可以调整 next.config.js 以显示 编译消息 正在开发中:

next.config.js

const { DefinePlugin } = require("webpack");const FriendlyErrorsWebpackPlugin = require("friendly-errors-webpack-plugin");常量地址 = 要求(地址");const { LOCALHOST, NODE_ENV, PORT } = process.env;常量 LOCALIP = 地址.ip();常量插件 = (isServer) =>{常量插件 = [];如果(!isServer){插件.push(/* 可选 -- 将 ENVS 附加到客户端进程 */新的定义插件({process.env":{本地主机:JSON.stringify(本地主机),NODE_ENV: JSON.stringify(NODE_ENV),},}));} 别的 {插件.push(/* 添加控制台编译消息 */NODE_ENV === 发展"&&新的 FriendlyErrorsWebpackPlugin({编译成功信息:{消息:[`本地开发版本:x1b[1m${LOCALHOST}x1b[0m`,LOCALIP&&`远程开发版本:x1b[1mhttp://${LOCALIP}:${PORT}x1b[0m`,].filter(布尔值),备注:[请注意,开发版本未优化.","要创建生产版本,请使用 x1b[1mx1b[32myarn exportx1b[0m.
",],},清除控制台:假,}));}返回 plugins.filter(Boolean);};模块.exports = {webpack(配置,{ isServer }){/* 添加自定义插件到客户端和/或服务器 */config.plugins.push(...plugins(isServer));/* 将新配置返回到下一个 */返回配置;},};

现在我们已经设置好了所有东西,我们可以运行 yarn export 来构建项目并将其导出到 out 目录,然后我们可以通过以下方式运行本地暂存环境运行 yarn start.访问打印在查看上述的工作回购示例.

如果您的项目仍有问题,请分享一个存储库;否则,将很难帮助您进行故障排除.

I have done development of Next Js application and as of now I have done auto deployment using vercel

Things are fine as of now.. But here came the requirement that I need to build the Next Js application and share the build folder with the team for deployment in server.

The commands I have followed,

npm run build & npm run export

And the above one creates the out directory.. So how to run this out directory in my local machine to check whether the build folder is working as expected before sharing with the team?

Folder structure of out directory:

 -> out

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

So anyone could kindly please help me how can I run this generated build folder (out) to check whether the developed Next Js application works fine in my local machine after which I can share the same build folder to the team?

To be specific I would like to know how exactly I can build the next js application in my local and then to test that built folder in my local that will run the application and can share the working build to anyone in team.

Raised issue here https://github.com/vercel/next.js/discussions/16439 but that didn't help in anyway..

解决方案

The official Next static export example uses serve, to "serve" the out directory. Since the out directory is just a bunch of static files, you need some sort of connection layer to the outside world/internal network. You could use something like nginx to the serve these assets (which eliminates the need of having to run two web servers). But, if you're looking for an easy way to run a local staging build, then you'll need to use some sort of web server: express, http-server or serve to name a few.

...and can share the working build to anyone in team.

If you're remote and connecting to a WAN, then anyone from your team can visit the staging build (eg: http://wanlocalip:3000 -- you can use address to print out a console message). If you're not connecting to a WAN and if you don't have your own server, then you'll have to create a remote staging environment using a 3rd party service like vercel, AWS, or Digital Ocean to name a few.


With that out of the way, let's take the official with-static-export example and set up a custom express server.

First, we'll add a few dependencies: yarn add chalk dotenv express

Adjust the package.json file scripts to be:

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

Then we'll create a server.js file in the root directory:

server.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(
      `
${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}`)}
`
    );
  } else {
    console.err(`
Unable to start server: ${err}`);
  }
});

Optionally we can adjust the next.config.js to display a compilation message in development:

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[1mx1b[32myarn exportx1b[0m.
",
            ],
          },
          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;
  },
};

Now that we have everything set up, we can run yarn export to build and export the project to the out directory, then we can run a local staging environment by running yarn start. Visit one of the addresses printed in the console.

Local

WAN (only accessible to those connected to a LAN connection within the WAN)


Click here to see a working repo example of the above.

If you're still having trouble with your project, then please share a repository; otherwise, it's going to be very difficult to help you troubleshoot.

这篇关于如何运行 Next Js 应用程序构建(输出)目录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆