如何通过svelte访问本地json文件? [英] How to access local json file via svelte?
本文介绍了如何通过svelte访问本地json文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
现在我使用 onMount 异步函数来访问
For now I use onMount async function to access
const dataAPI = './jsfwperf.json';
let data = [];
onMount(async () => {
const res = await fetch(dataAPI)
.then(res => res.json())
.then(data => {
console.log(data)
})
.catch(err => console.error(err));
});
但在终端显示文件丢失
bundles src/main.js → public\build\bundle.js...
[!] Error: Unexpected token (Note that you need @rollup/plugin-json to import JSON files)
文件位置与我使用的 app.svelte 相同.如何通过 svelte 正确访问本地 json 文件?
File location is the same as app.svelte that I used. How can I proper access local json file via svelte?
推荐答案
在命令行中:
cd yourproject
npm install @rollup/plugin-json --save-dev
编辑 rollup.config.js
文件:
// add at the beginning of the file :
import json from '@rollup/plugin-json'
//...
// under the plugin line :
plugins: [
json({
compact: true
}),
//...
在你的苗条组件中:
<script>
import * as myjson from './test.json'
</script>
<p>{myjson.mykey}</p>
这篇关于如何通过svelte访问本地json文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文