gpt4 book ai didi

vue.js - 如何使用 Vite 从公共(public)目录导入 JSON 文件?

转载 作者:行者123 更新时间:2023-12-02 01:26:51 25 4
gpt4 key购买 nike

我有一个 Vue3/Vite 项目,其中一些数据必须从外部 JSON 文件中读取。

但是当我构建项目时 - JSON 文件被捆绑。

我需要将 JSON 文件保存在外部。

我尝试过的:

  1. 第一次尝试vite.config.ts
export default defineConfig({
optimizeDeps:{
exclude: ['myfile.json'] // then i tried ['**/myfile.json']
},
})
  1. 第二次尝试

vite.config.ts

assetsInclude: ['**/*.json'],
assetsInlineLimit: 0,
  1. 第三次尝试

App.vue

let jsonData = import.meta.glob('/public/assets/myfile.json')

我做错了什么 - 有没有一种简单的方法可以将 JSON 文件保存在外部?

最佳答案

Nvm,在Vite中你直接使用fetch来抓取数据,而不是import,即not possible顺便说一句。

这个讨论有一个 official answer

这样就可以实现你想要的了

<script setup>
import { onMounted } from "vue";

onMounted(async () => {
const response = await fetch("/file.json");
const file = await response.json();
console.log("cool file", file);
});
</script>

结构如下

enter image description here

file.json 正在

{
"name": "bob",
"age": 29
}

结果如下

enter image description here

关于vue.js - 如何使用 Vite 从公共(public)目录导入 JSON 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74344683/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com