如何在應用程式中忽略整個資料夾的 Next.js 方法?
P粉682987577
P粉682987577 2023-12-30 18:49:17
0
2
491

在接下來的 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粉682987577
P粉682987577

全部回覆(2)
P粉662361740

您可以在 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',
      });
}
P粉321584263

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

熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!