ueeieiie
ueeieiie

Reputation: 1562

What is the way to use dynamic imports?

I'm trying to use Dynamic Imports - import()

I've read this dynamic-import documentations and watched this chrome devtools video,

and still couldn't find the right way of doing it correctly.

Error:

Uncaught (in promise) ReferenceError: module is not defined

Boilerplate:

I've created a new project.

no webpack, no task runners.

just running a server with http-server node package with those files:

  1. index.html
  2. index.js
  3. a.js

index.html:

<button id="btn"> Lazy load a module</button>
<script src="index.js"></script>

index.js:

const btn = document.querySelector('#btn');

btn.addEventListener('click', event => {
  import('./a.js').then(module => { console.log(module) })
});

a.js

module.exports = { type: 'LazyModule'}

What am I missing here?

Upvotes: 3

Views: 845

Answers (1)

coagmano
coagmano

Reputation: 5671

the dynamic import function is from the ECMAScript standard while module.exports is a part of commonjs loaders (like browserify)

To get this to work you want to use ES Module syntax everywhere:

index.html: Add type="module" to entry file

<button id="btn"> Lazy load a module</button>
<script src="index.js" type="module"></script>

index.js: This one is fine

a.js

export const type = 'LazyModule';

It's important to note the method of module resolution in the browser is the same as for any other asset (links to html files, images, etc.)

Upvotes: 2

Related Questions