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?

3
  • ES 6 modules are not supported by any browser, so I assume that you're using Babel, right? Jun 4, 2017 at 14:15
  • yes, I am using Babel
    – Chedy2149
    Jun 4, 2017 at 14:20
  • 1
    Are you using any bundler, like webpack, Browserify or Rollup? Jun 4, 2017 at 14:22

1 Answer 1

27

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?

6
  • 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? Jun 4, 2017 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. Jun 4, 2017 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. Jun 4, 2017 at 15:04
  • 1
    @estus That sounds very good! Yes, I was asking from the native perspective, without bundlers. Thanks! Jun 4, 2017 at 15:07
  • @MichałPerłakowski is there a way to access all functions of a module in the browser
    – MAS
    Nov 18, 2020 at 1:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.