Marco
Marco

Reputation: 501

Vue 3.0 import not static?

I'm on my way to build my first vue frontend, i just found out that when i import json files via import statements they are fixed in the build and can't be "dynamic". For example:

...
// youtube channel info fetched and cached by PHP
import channel from '@/../public/cache/channel.json' 
import playlists from '@/../public/cache/playlists/' 

export default {
  name: 'Home',
  components: {
    configuration, channel, playlists
  },
  data(){
    console.log(configuration)
    console.log(channel)
    console.log(playlists)
    return{
      configuration, channel, playlists
    }
  }
}

where playlists loads an index.js that contains playlists (file generated by PHP):

import PLnsP5eFkpFGioJZFSaVRRxy1S7cJ6PWeG from './playlist-PLnsP5eFkpFGioJZFSaVRRxy1S7cJ6PWeG.json'
...
export default{
PLnsP5eFkpFGioJZFSaVRRxy1S7cJ6PWeG,...}

My thought was that if I do the build I will still be able to generate these files on the server and Vue resp. the generated code will refer to them - unfortunately this is not the case and I had to learn that vue imports all imports one to one fix during the build (what the name says and is obvious yes) and combines them in a corresponding js file, which makes it impossible for me to link another channel or map to new videos / playlists afterwards.

Is it even possible to "stay dynamic" via imports or do I have to get the json's via axios or something (even if the files are on the same host)?

Upvotes: 0

Views: 197

Answers (1)

Michal Levý
Michal Levý

Reputation: 37813

You have to use Axios/fetch for that...

Imports are indeed static - the content of the imported file is included in the app bundle (at built time)

There is something called dynamic imports but it is the technique intended for "load only what you need at the time you need it". The content of the import is still determined at build time (at build time webpack prepares the file which will be loaded at runtime)

So if you want the content to be dynamic, loaded to the app at runtime, the only solution is to use Axios/fetch and keep the data "outside" of the app itself...

Upvotes: 1

Related Questions