搜索

首页  >  问答  >  正文

如何在应用程序中忽略整个文件夹的 Next.js 方法?

在接下来的 13 天内,当 nextConfig.output 为“export”时,app/api 文件夹会在构建过程中产生错误。

在我的项目中,我需要根据环境变量不同的构建类型。

当“output”为“export”时,有什么方法可以在构建过程中忽略“api”文件夹吗?

当我使用 nextConfig.output 作为“导出”运行构建时,出现以下错误:

导出在以下路径上遇到错误: /api/revalidate/route: /api/revalidate

src/app/api/revalidate/route.ts 文件

import { NextRequest, NextResponse } from 'next/server';
import { revalidateTag } from 'next/cache';
 
export async function GET(request: NextRequest) {
  const tag = request.nextUrl.searchParams.get('tag');
  if(tag){
    revalidateTag(tag);
  }
  return NextResponse.json({ revalidated: true, now: Date.now() });
}

Next.config.js

/** @type {import('next').NextConfig} */
const nextConfig = {
  output: process.env.NEXT_OUTPUT_MODE,
};

module.exports = nextConfig;

可复制的存储库

这里是重现此错误的存储库 https://github.com/zeckaissue/next-export-api-crash

P粉682987577P粉682987577421 天前599

全部回复(2)我来回复

  • P粉662361740

    P粉6623617402023-12-31 10:31:51

    您可以在 Next.js 配置文件 (next.config.js) 中使用忽略选项。 如果您还没有创建一个配置文件,则必须创建一个配置文件。 打开next.config.js文件并添加以下代码:

    module.exports = {
      webpack: (config, { isServer }) => {
        if (!isServer) {
          config.module.rules.push({
            test: /YOUR FOLDER NAME\/.*/,
            loader: 'ignore-loader',
          });
    }

    回复
    0
  • P粉321584263

    P粉3215842632023-12-31 00:13:46

    我找到了 ignore-loader 的解决方法。但也许有更好的方法通过 next.js 的内置功能来实现我的目标

    这是我更新的 next.config.js

    /** @type {import('next').NextConfig} */
    const nextConfig = {
      output: process.env.NEXT_OUTPUT_MODE,
      /**
       *
       * @param {import('webpack').Configuration} config
       * @param {import('next/dist/server/config-shared').WebpackConfigContext} context
       * @returns {import('webpack').Configuration}
       */
      webpack: (config) => {
        if (process.env.NEXT_OUTPUT_MODE !== "export" || !config.module) {
          return config;
        }
        config.module.rules?.push({
          test: /src\/app\/api/,
          loader: "ignore-loader",
        });
        return config;
      },
    };
    
    module.exports = nextConfig;
    
    

    回复
    0
  • 取消回复