20

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,501
  • 3
  • 30
  • 52

1 Answers1

20

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

import {send} from "./sender";
window.send = 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?

Michał Perłakowski
  • 80,501
  • 25
  • 149
  • 167
  • 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