Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 280
Chedy2149 Avatar asked Jun 04 '17 14:06

Chedy2149


People also ask

How do I use ES6 modules in browser?

Safari, Chrome, Firefox and Edge all support the ES6 Modules import syntax. Here's what they look like. Simply add type="module" to your script tags and the browser will load them as ES Modules. The browser will follow all import paths, downloading and executing each module only once.

Can browser read ES6?

It is called a “compiler” because it converts ES6 code to ES5 code so that as long as your browser can support ES5, you can use ES6 code safely.


1 Answers

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?

like image 194
Michał Perłakowski Avatar answered Oct 07 '22 21:10

Michał Perłakowski