javascript - 如何通过 svelte 访问本地 json 文件?

标签 javascript async-await svelte

现在我使用 onMount 异步函数来访问

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 文件?

最佳答案

在命令行中:

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
  }),

//...

在您的 slim 组件中:

<script>
import * as myjson from './test.json'
</script>

<p>{myjson.mykey}</p>

关于javascript - 如何通过 svelte 访问本地 json 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60779816/

相关文章:

javascript - Ace js替换文本

javascript - 如何从 JavaScript 中的事件处理程序调用公共(public)函数?

javascript - 在 MapReduce MongoDB 中按键对数据进行分组

href - 如何在 SvelteKit 中使用 Relative Href?

javascript - Google Map Api 不显示在 ng-view 中

c# - ASP.NET 4.6 异步 Controller 方法在等待后丢失 HttpContext.Current

c# - 如何立即从异步循环返回值?

c# - 对使用异步调用的 MassTransit 消费者进行单元测试

javascript - 在 Svelte 中获取对组件根元素的引用

node.js - 我想使用 nginx 在同一台服务器上部署后端和前端单独的应用程序