Search code examples
javascriptecmascript-6es6-modules

How to access functions defined in ES6 module in a browser's JavaScript console?


I have a function that is defined in an ES6 module (sender.js) as follows:

function send() {
   // do stuff
}
export {send};

This module is then used in the application's main JavaScript file app.js as follows:

import {send} from "./sender"

The send function is available in the app.js file, however it is not in Firefox's Javascript console:

> send
ReferenceError: send is not defined

How can I import the send function in the JavaScript console?


Solution

  • You can set the specific function as global by assigning it to the global object – in browsers it's window.

    // To make one function available in the browser:
    import { send } from "./sender.js"; // Might omit `.js` if using a bundler.
    window.send = send;
    
    // To make all functions available:
    import * as sender from "./sender.js";
    window.sender = sender;
    
    // In the browser console:
    window.sender.send()
    

    Note that while it might be useful in debugging, you shouldn't use that in production code – see Why are global variables considered bad practice?