23

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?

Chedy2149
  • 2,821
  • 4
  • 33
  • 56

1 Answers1

26

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?

marcelocra
  • 2,094
  • 2
  • 24
  • 37
Michał Perłakowski
  • 88,409
  • 26
  • 156
  • 177
  • 1
    What I'm wondering is, since `send` is declared in a file, not being wrapped in any function, shouldn't that be a global? Is this specific to files loaded via `import`? – Ionică Bizău Jun 04 '17 at 14:14
  • @IonicăBizău I think it depends on what bundler the OP is using. This behavior seems logical to me, because there's no need for an app to expose any functions. For example, [Rollup complies the code in question to an empty file](https://goo.gl​/PM4zOq). – Michał Perłakowski Jun 04 '17 at 14:21
  • 3
    @IonicăBizău Yes, it is specific to them. The files that are loaded with import are modules, and modules have their own scopes. That's the purpose of modules - being modular and not pollute global scope. – Estus Flask Jun 04 '17 at 15:04
  • 1
    @estus That sounds very good! Yes, I was asking from the native perspective, without bundlers. Thanks! – Ionică Bizău Jun 04 '17 at 15:07
  • @MichałPerłakowski is there a way to access all functions of a module in the browser – MAS Nov 18 '20 at 01:36
  • @MAS Added details on how to import all functions from a module. – marcelocra May 12 '23 at 22:24