带有动态文件名的 Nuxt 服务器 api 导入功能不起作用

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

在 Nuxt 服务器 api 中,我想从资产文件夹中导入一个具有动态名称的静态 json 文件

export default defineEventHandler(async (event) => {
  const query = getQuery(event)
  const path = query.path as keyof typeof FilePaths

  enum FilePaths {
    "home" = "../../assets/json/home.json",
    "article-1" = "../../assets/json/article-1.json",
    "article-2" = "../../assets/json/article-2.json",
    "article-3" = "../../assets/json/article-3.json",
    "article-4" = "../../assets/json/article-4.json",
    "article-5" = "../../assets/json/article-5.json",
    "article-6" = "../../assets/json/article-6.json",
  }

  const filePath = FilePaths[path]
  const page = await import(filePath, { assert: { type: 'json' } })
})

我收到此错误

[nuxt] [request error] [unhandled] [500] Module "file:///D:/folder/assets/json/article-1.json" needs an import assertion of type "json"

如果我传递硬编码字符串,它就会起作用

await import("../../assets/json/article-1.json")

但不要使用变量或连接字符串

我怎样才能动态地做到这一点?我不想导入所有文件,或者对它们的路径进行硬编码

我尝试过:

  • 指定可能的文件名
  • 按照错误提示添加断言选项
javascript nuxt.js dynamic-import
1个回答
0
投票

我通过使用 fs.readFile 来管理它

export default defineEventHandler(async (event) => {
  const query = getQuery(event)
  const path = query.path

  const fs = await import('fs')
  const jsonPromise = new Promise((res, rej) => {
    fs.readFile(
      `./assets/json/${path}.json`, 
      (err, data) => {
        if (err) {
          rej(err)
          throw err
        }

        const dataString = data.toString('utf-8')
        const dataJson = JSON.parse(dataString)
        res(dataJson)
      }
    )
  })

  const page = await jsonPromise

  return page
})

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