Next.js 如何忽略应用程序中的完整文件夹?

Rob*_*ari 5 javascript next.js static-site-generation

在接下来的 13 日,当 nextConfig.output 为“export”时,app/api 文件夹会在构建期间创建错误。

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

当“输出”为“导出”时,有什么方法可以在构建过程中忽略“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() });
}
Run Code Online (Sandbox Code Playgroud)

Next.config.js

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() });
}
Run Code Online (Sandbox Code Playgroud)

可复制的存储库

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

Rob*_*ari 3

我找到了使用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;

Run Code Online (Sandbox Code Playgroud)

  • 目前这似乎是最好的解决方案 (2认同)