10

I'm loading a javascript file using jquery with the usual:

// file application.js
$.getScript("module.js", function(data, textStatus, jqxhr) { ... });

So far so good. Except that module.js uses a function declared in another module i.e., it contains the statement:

// file module.js
import { myFunction } from './library.js';

When the browser loads my application, it complains that:

Cannot use import statement outside a module

Is there a way to load the script module.js as a module?

Thanks

Daniele Pallastrelli
  • 2,430
  • 1
  • 21
  • 37
  • Bear in mind import [isn't supported by any of the MS browsers](https://caniuse.com/#feat=es6-module-dynamic-import). Your likely going to want to use something like [webpack](https://webpack.js.org/) to transpile your code into something with better support. – Liam Nov 06 '19 at 08:26
  • Thank you @Liam . Let's say my application runs only on chrome: is there a way to solve my problem? – Daniele Pallastrelli Nov 06 '19 at 08:31
  • 1
    Well one issue is, module.js does not include the code for library.js. So you can't just load that one js file. Again precompilation should solve this as it can bundle the whole application into one file. I'd still be looking at webpack or some other compiler – Liam Nov 06 '19 at 09:04

2 Answers2

1

Try loading the script in the html file as

  <script type="module" src="module.js"></script>
rokiuk
  • 11
  • 1
0

You cannot load other modules unless you declare your own script also a module.

So if your javascript is inline code you can do:

<script type="module"> ... $.getScript("module.js", function(data, textStatus, jqxhr) { ... }); ... </script>

The problem I ran into using this approach is, while using jQuery you also have to also import jQuery as Module.

There's another thread on how to do that here I liked the solution from Yukulélé.

Depending on how many other scripts you have this might be a load of work, or if you're using a lot of external scripts this might not work at all.

woif00
  • 1
  • 1