首页 > 解决方案 > Next.js - “纱线构建”失败

问题描述

当我尝试构建用于生产的 Next.js 应用程序时,出现以下错误:

在此处输入图像描述

似乎“API_KEY”未定义。无法从 publicRuntimeConfig 解构此属性。此错误发生在我使用getStaticPropsgetStaticPaths内置函数的页面上。

这是我的 next.config.js:

const withPlugins = require("next-compose-plugins");
const withCSS = require("@zeit/next-css");
const withSass = require("@zeit/next-sass");
const withBundleAnalyzer = require("@next/bundle-analyzer");
const nextRuntimeDotenv = require("next-runtime-dotenv");

const withConfig = nextRuntimeDotenv({ public: ["API_URL", "API_KEY"] });

const nextConfig = {
    analyzeServer: ["server", "both"].includes(process.env.BUNDLE_ANALYZE),
    analyzeBrowser: ["browser", "both"].includes(process.env.BUNDLE_ANALYZE),
    bundleAnalyzerConfig: {
        server: {
            analyzerMode: "static",
            reportFilename: "../bundles/server.html",
        },
        browser: {
            analyzerMode: "static",
            reportFilename: "../bundles/client.html",
        },
    },
    publicRuntimeConfig: {
        PROXY_MODE: process.env.PROXY_MODE,
        API_URL: process.env.API_URL,
        API_KEY: process.env.API_KEY,
        STATIC_PATH: process.env.STATIC_PATH,
    },
};

module.exports = withConfig(
    withPlugins([[withCSS], [withSass], [withBundleAnalyzer]], nextConfig)
);

我研究了官方文档和谷歌类似的问题,但似乎没有结果。任何想法为什么 Next.js 纱线构建失败?

标签: next.js

解决方案


从文档中你可以找到这个。A page that relies on publicRuntimeConfig must use getInitialPropshttps://nextjs.org/docs/api-reference/next.config.js/runtime-configuration)我认为你应该把它放在别的地方。检查环境变量部分https://nextjs.org/docs/api-reference/next.config.js/environment-variables


推荐阅读