简体   繁体   中英

Ways to import a JSON file in public folder in Vue-CLI

I want to import a JSON file to use it, I need it to modify it in the future so I put it in public folder not assets , When I refer to it like this import JSON from../../public/Data.json it works but I don't think so after building project can be resolved because after building there is no public folder. So I tried this:

let addr = process.env.BASE_URL;
import JSON from `${addr}Data.json`;

But It throws an error: SyntaxError I'm confused now which way is the best and is there another way?

The assets in the public folder are copied as is to the root of the dist folder. In your code, you can reference it just as /Data.json (if your app is deployed at the root of the domain).

Eg

async someMethod() {
    const baseUrl = process.env.BASE_URL;
    const data = await this.someHttpClient.get(`${ baseUrl }/Data.json`);
}

If you want to import the JSON as you have tried, I suggest to put it somewhere in the src folder and import from there

Eg

import data from '@/data/someData.json'

console.log(data);

I came across this because I was doing a stand alone SPA that I wanted to run with no DB and keep the config in a JSON file. The import statement above works great for a static conf file, but anything imported like that gets compiled with the build, so even though your someData.json will exist in the public folder you won't see any changes in your dist because it's actually reading a JS compiled file.

To get around this I:

  1. Convert the JSON file into a simple JS variable in a conf.js file: eg
var srcConf={'bGreatJSON':true};
  1. In index.html, did
<script src='./conf.js'>
  1. Now that the JS variable has been declared in my Vue component I can just look for the window.srcConf and assign it if it exists in mounted or created:
if(typeof window.srcConf!='undefined')
  this.sConf=window.srcConf;

This also avoids the GET CORS issue that others posts I've seen runs into, even in the same directory I kept getting CORS violations trying to do an axios call to read the file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM