在getStaticProps中使用fs.readFile时,nextjs构建将花费将近2个小时来完成

时间:2020-10-22 14:19:50

标签: javascript next.js

我对next.js相当陌生,但是我目前在我的项目中使用它来生成静态文件。从getStaticPaths返回的特定动态全部路由的静态路径超过5000条。

我目前正在预构建阶段将数据提取并缓存到文件系统中,没有问题。但是当我运行next build时,从该动态路由生成静态文件将花费很多时间。

import fs from 'fs';
import { promises } from 'util';

const readFile = promisify(fs.readFile);
const readCache = async (cacheKey) => {
  try {
    // cache directory is not included here
    const content = await readFile(`${cacheKey}.json`, { encoding: 'utf-8' });
    return JSON.parse(content);
  } catch (e) {
    console.log(`Error while reading file - ${cacheKey}.json`);
  }
};

export async function getStaticPaths() {
  try {
    const keywords = await readCache('LESSONS_CACHE');
    const letters = getLetters(keywords);
    const paths = letters
      .map((letter) => ({
        params: { slugs: [encodeURIComponent(letter)] }
      }))
      .concat(
        keywords.map((k) => ({
          params: { slugs: [encodeURIComponent(k.letter), k.slug] }
        }))
      );

    return {
      paths,
      fallback: false
    };
  } catch {
    return {
      paths: [],
      fallback: false
    };
  }
}

export async function getStaticProps({ params }) {
  const [, slug] = params.slugs;
  let keyword = null;
  const promises = [readCache('LESSONS_CACHE')];

  if (slug) {
    promises.push(readCache('LEARN_CACHE'), readCache('IMAGES_CACHE-map'));
  }

  try {
    const [keywords, ...rest] = await Promise.all(promises);
    const letters = getLetters(keywords);

    if (slug) {
      const [units, images] = rest;
      keyword = keywords.find((k) => k.slug === slug);
      keyword.learn_units = keyword.learn_units.map((id) => {
        const unit = units.find((u) => u.id === id);
        unit.image = images[id] ?? null;
        return unit;
      });
    }

    return {
      props: {
        initialState: {
          lessons: {
            letters,
            keywords,
            keyword: slug && keyword ? keyword : null
          }
        }
      }
    };
  } catch (e) {
    console.log(e);
    return { props: { initialState: {} } };
  }
}

我做错了什么吗?任何反馈都将不胜感激。

0 个答案:

没有答案