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

9lowa7mx  于 2023-06-22  发布在  其他
关注(0)|答案(3)|浏览(231)

在接下来的13,当nextConfig.output为“export”时,app/API文件夹在构建过程中创建错误。
在我的项目中,我需要不同的构建类型取决于environnement变量。
当“输出”是“导出”时,有什么方法可以忽略“API”文件夹?
当我用nextConfig.output作为“export”运行build时,我得到了以下错误:
导出在以下路径上遇到错误:/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的存储库

f87krz0w

f87krz0w1#

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

sg2wtvxw2#

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

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

s2j5cfk03#

这是我的答案。

/** @type {import('next').NextConfig} */
const nextConfig = {
  output: process.env.NEXT_OUTPUT_MODE,
  exclude: [/node_modules/, /api/], // Add this line to exclude the api folder
};

module.exports = nextConfig;

相关问题