vue.jsvuejs2vue-clivue-cli-3

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 ?


Solution

  • 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).

    E.g

    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

    E.g.

    import data from '@/data/someData.json'
    
    console.log(data);