javascriptfirefoxdeveloper-tools

variable not defined in developer tools console


I have been using the console to examine variables but it has stopped working for me and I do not know why.

To illustrate the problem I have the following files which run locally on Apache so I access it at localhost/path/to/index.html.

index.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script type="module" src="./javascript/main.js"></script>
    <title>Document</title>
</head>
<body>
    <h1>...</h1>
</body>
</html>
main.js:

console.log("from main.js");
let sillyName = { number: 7 };

In Firefox and Chrome developer tools console if I start typing "sillyName" I would expect it to autocomplete to "sillyName" and show the value of that variable but I get an error as seen in this screenshot:

Firefox console showing the error

Obviously I am doing something differently to what I normally do but I can not work out what. Any help would be appreciated.


Solution

  • The problem is that sillyName is defined in a ESModule which have its own context.

    To make sillyName available in the console, you should define the variable in the available window global object available in the module context:

    // file: main.js
    window.sillyName = { number: 7 };
    

    Also, I recommend using the mjs extension: main.mjs.

    <script type="module" src="main.mjs"></script>
    
    // file: main.mjs
    import { myFunction } from 'modules/some/module.mjs';
    
    // Export something to other modules:
    export const something = myFunction();
    
    // Export something to CommonJS if in browser:
    // window.something = something;
    
    // Or like this that works even on back-ends:
    (typeof window == 'object') && ( window.something = something );
    
    // Export more stuff from another module:
    export { someClass, anotherClass } from 'modules/another/module.mjs';
    

    If you change the type attribute of the <script> to text/javascript then the sillyName will be automatically attached to the current window object but the script will no longer be a module.

    The following guide should be very useful to understand the problem: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules

    From the above guide:

    Last but not least, let's make this clear — module features are imported into the scope of a single script — they aren't available in the global scope. Therefore, you will only be able to access imported features in the script they are imported into, and you won't be able to access them from the JavaScript console, for example. You'll still get syntax errors shown in the DevTools, but you'll not be able to use some of the debugging techniques you might have expected to use.