Reputation: 1562
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.
Uncaught (in promise) ReferenceError: module is not defined
I've created a new project.
no webpack, no task runners.
just running a server with http-server node package with those files:
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
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