Plu*_*ugz 4 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));
});
Run Code Online (Sandbox Code Playgroud)
但是在终端它显示文件丢失
bundles src/main.js ? public\build\bundle.js...
[!] Error: Unexpected token (Note that you need @rollup/plugin-json to import JSON files)
Run Code Online (Sandbox Code Playgroud)
文件位置与我使用的 app.svelte 相同。如何通过 svelte 正确访问本地 json 文件?
Jef*_*rod 10
在命令行中:
cd yourproject
npm install @rollup/plugin-json --save-dev
Run Code Online (Sandbox Code Playgroud)
编辑rollup.config.js文件:
// add at the beginning of the file :
import json from '@rollup/plugin-json'
//...
// under the plugin line :
plugins: [
json({
compact: true
}),
//...
Run Code Online (Sandbox Code Playgroud)
在你的苗条组件中:
<script>
import * as myjson from './test.json'
</script>
<p>{myjson.mykey}</p>
Run Code Online (Sandbox Code Playgroud)