Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access local json file via svelte?

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

But in terminal it shows that file is missing

bundles src/main.js → public\build\bundle.js...
[!] Error: Unexpected token (Note that you need @rollup/plugin-json to import JSON files)

File location is the same as app.svelte that I used. How can I proper access local json file via svelte?

like image 508
Plugz Avatar asked Mar 20 '20 18:03

Plugz


1 Answers

In command line :

cd yourproject
npm install @rollup/plugin-json --save-dev

Edit the rollup.config.js file:

// add at the beginning of the file :
import json from '@rollup/plugin-json'

//...

// under the plugin line :
plugins: [
  json({
    compact: true
  }),

//...

In your svelte component :

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

<p>{myjson.mykey}</p>
like image 167
JeffProd Avatar answered Sep 27 '22 03:09

JeffProd