Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'Uncaught ReferenceError: ... is not defined' when calling a class (defined in module) from a browser console, JS

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
like image 349
helpME1986 Avatar asked Oct 16 '25 06:10

helpME1986


1 Answers

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);
like image 76
Aluan Haddad Avatar answered Oct 18 '25 02:10

Aluan Haddad



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!