通过 NPM 包在 Next.js 中动态加载 JSON 时出现问题

问题描述 投票:0回答:1

我有一个 TypeScript 项目,它根据作为参数传递给我的

PlatformConfigurationFactory
文件中的 getInstance 函数的枚举值动态加载 json 配置文件。

  public static async getInstance(
    platform: Platform
  ): Promise<PlatformConfiguration> {
    const jsonData = await this.configurationRepository.getConfig(platform);
    if (!jsonData) {
      throw new Error("Configuration data not found");
    }

    this.jsonValidator.loadSchema();
    if (!this.jsonValidator.isValid(jsonData)) {
      throw new Error("Invalid JSON data according to schema");
    }

    return this.fromJson(jsonData);
  }

JsonConfigurationRepository
文件用于读取文件并以Json形式返回其内容。

import { IConfigurationRepository } from "../../application/interfaces/IJsonConfigurationRepository";
import { Platform } from "../../core/domain/Platform";
import fs from "fs/promises";
import path from "path";

export class JsonConfigurationRepository implements IConfigurationRepository {
  async getConfig(platform: Platform): Promise<any> {
    const fileName = `${platform}-config.json`;
    const filePath = path.resolve(__dirname, "../../data", fileName);

    try {
      const fileContent = await fs.readFile(filePath, "utf-8");
      return JSON.parse(fileContent);
    } catch (error) {
      console.error(`Error loading configuration for ${platform}:`, error);
      return null;
    }
  }
}

这些文件存储在

./src/data
目录中,当 TypeScript 在
./dist
文件夹中构建文件时,由于我下面的配置,json 文件就会出现。

{
  "compilerOptions": {
    "target": "ESNext",                          
    "experimentalDecorators": true,              
    "emitDecoratorMetadata": true,               
    "module": "ESNext",                          
    "rootDir": "./src",                          
    "moduleResolution": "Node",                  
    "baseUrl": "./",                             
    "paths": {                                   
      "@mylib/*": ["src/*"]
    },                                      
    "resolveJsonModule": true,                   
    "declaration": true,                         
    "declarationMap": true,                      
    "outDir": "./dist",                          
    "skipLibCheck": true                         
  },
  "include": [
    "src/**/*",
    "data/**/*.json",
  ],
  "exclude": [
    "node_modules",
    "**/*.spec.ts",
    "**/*.test.ts"
  ]
}

测试没问题,当我调用我的工厂时,它返回我作为参数传递的平台的配置:

    const config = await PlatformConfigurationFactory.getInstance(
      Platform.Facebook
    );

此项目随后作为 NPM 包存储在 Gitlab 的包注册表中,我通过

npm i @mylib/platform-configurations
将其安装在 Next.js 14 项目中。

但是当我在 Next.js 中调用相同的代码时出现错误:

    const config = await PlatformConfigurationFactory.getInstance(
      Platform.Facebook
    );

错误:

加载 facebook 配置时出错:[错误:ENOENT:没有这样的文件或目录,打开 '/Users/me/workspace/nextjs/.next/server/json/facebook-config.json'] { 错误号:-2, 代码:'ENOENT', 系统调用:'打开', 路径:'/Users/me/workspace/nextjs/.next/server/json/facebook-config.json' } ⨯ 错误:未找到配置数据 在 Generator.next() 处 摘要:“2762426514” ⨯ 错误:未找到配置数据 在 Generator.next() 处 摘要:“2762426514”

代码尝试加载错误路径中的文件,而不是加载已安装包中

dist/data
中的文件。请问我该如何解决这个问题?

javascript node.js json typescript next.js
1个回答
0
投票

我不知道这是否适合您的问题,但您可以这样做:

 const isDevelopment = process.env.NODE_ENV === 'development';
 const filePath = isDevelopment ?
      path.resolve(__dirname, "../../data", fileName) :
      require.resolve(`@mylib/platform-configurations/data/${fileName}`);

基本上检查你是否正在开发,所以使用你现在做的事情,或者解决正确的路径

© www.soinside.com 2019 - 2024. All rights reserved.