ramin
ramin

Reputation: 968

dynamic import of cross origin script files

I want to use javascripts dynamic import function. However, when I specify a whole url to import I get an error:

Cannot find module 'https://....

tho I know the resource is available. Is import restricted to same-origin script files (therefor all modules start with ./)?

On the other hand, I can dynamically create a script element and set the source to anything, and when its loaded all its functions (not a module) are in the global scope.

I would like to have the benefits of both :) loading script from cross origins but keep them in module structure.


since there are 2 comments thanks to the tips I found it seemed to be a problem with how parcel bundles, imports...

I could not find a way how to do it with parcel 2.7.0.

So is there a way to load a module, from a script tag that I create, set the type as a module and the src, to what I need.


Something slightly nicer then: const importPromise = eval("import(scriptUri)") which actually does the job

Upvotes: 1

Views: 1264

Answers (1)

dangarfield
dangarfield

Reputation: 2330

I believe this may be due to a lot of bundlers not being able to run dynamic imports:

Well, the issue isn't the bundlers not supporting them, but the usage of them is somewhat confusing to many, evident by the amount of tickets open in the various repos.

There are a few work arounds, but I think you may need to post a detail setup for us to help.

For now, I'd suggest (if possible), using defined strings in if conditions to get started. It's not ideal, but you may find yourself going in circles otherwise. If you provide the exact urls, that may help, but this is a good example:

function localeDynamicImport (locale) {
  if (lang === 'en') {
    return import('./locales/en.js');
  }

  if (lang === 'zh') {
    return import('./locales/zh.js');
  }
}

Other options include:

  • Pure ES6 module without a bundler
<script type="module">
  import * as THREE from 'https://cdn.skypack.dev/[email protected]'
</script>
import(/* webpackIgnore: true */ 'http://example.com/some-module/some-module.bundle.js').then(module => console.log(module.default));

Upvotes: 2

Related Questions