Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to asynchronously import components in VueJS by full URL

I need to import a Vue component asynchronously by the full URL opposed to relative URL. The following example taken from the VueJS documentation works just fine for components within the same project

Vue.component(
  'app-component-one',
  () => import('./component-from-app-one')
)

However, my goal is to import components from a separate project that's deployed on the same server. I was hoping I could use the full URL and do something like...

Vue.component(
  'app-component-two',
   () => import ('http://sample-domain.com/project-2/components/component-from-app-two.vue')
)

but it results in and error:

This dependency was not found:
* http://sample-domain.com/app-2/components/component-from-app-two.vue in ./node_modules/babel-loader/lib!./node_modules/vue-loader/lib/selector.js?type=script&index=0&bustCache!./src/components/SampleComponent.vue

Is importing components by full URL possible? Thanks in advance!

like image 577
ncutt010 Avatar asked Nov 08 '22 12:11

ncutt010


1 Answers

The example you referenced from the Vue website is leveraging the code-splitting functionality from WebPack, so it will NOT work to load files that are not part of the same project.

What you are trying to do is typically called "dynamic/asynchronous ES6 module loading". Not to get too deep in to it.. but the current import blah from X only support static imports. If you care more about the nitty-gritty details of this.. there is a TC39 proposal for dynamic imports in JS

In the mean time... us mortals have to depend on tools like SystemJS which will do exactly what you are asking for.

But like @divine mentioned... you need some type of build-process that generates the stand-alone Vue component. You can use either WebPack or RollUp to export it as a UMD and the use SystemJS to import that component by referencing the full URL (you could even import it from a different domain! assuming that domain supports CORS)

like image 132
Maurice Avatar answered Nov 12 '22 14:11

Maurice