I have a file class.js
//implementation details
const _stackCollection = new WeakMap();
//interface
export class Stack {
constructor() {
_stackCollection.set(this, []);
}
get count() {
return _stackCollection.get(this).length;
}
pop() {
if (this.count === 0)
throw new Error('Nothing to pop');
return _stackCollection.get(this).pop();
}
peek() {
if (this.count === 0)
throw new Error('Nothing to peek');
return _stackCollection.get(this)[this.count - 1];
}
push(e) {
_stackCollection.get(this).push(e);
return;
}
}
and a module that imports given class looks like this module.js:
import {Stack} from './class.js';
The index.html looks like this:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<h1>hello world</h1>
<script type="module" src='module.js'></script>
</body>
</html>
When I try to initialize the instance of Stack in a console I get the following error. There are many questions regarding the given error but I can not see anything would help me:
const stack=new Stack()
Uncaught ReferenceError: Stack is not defined
at <anonymous>:1:13
Declarations in a module are scoped to that module. If you want to access them, you need to import them.
To use such an export in your browser console, you need to import it or bind it to a global variable.
global (Note that this defeats the purpose of modules and should only be used for ad hoc testing)
export class A {}
// TODO: remove this
window.A = A;
With the proposed dynamic import syntax:
// browser console:
import('./a.js').then(console.log);
With SystemJS
// browser console:
SystemJS.import('./a.js').then(console.log);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With