As far as I understand it, if I create an ES6 module, I can only import it from code that is itself a module. This means non-module code, i.e. inline Javascript, or the Chrome dev tools console can never access code that is in a module.
Is that true? Is there any way around this because it seems like a fairly extreme limitation.
You can use dynamic import within Chrome's console.
import('path/to/module.js').then(m => module = m)
// [doSomething] is an exported function from [module.js].
module.doSomething()
You can register the function or variable in the global namespace with a line like window.myFunction = myFunction
or window.myVariable = myVariable
. You can do this in the module where myFunction
or myVariable
are declared or do it in a separate module where they have been imported.
Once you've done this, you will be able to use myFunction
and myVariable
from the Chrome DevTools console.
For example:
import myModule from '/path/to/module.js';
window.myModule = myModule;
// in the console:
myModule.foo();
(Credit to @Evert for providing this solution in a comment, albeit in a rather roundabout way that took me a while to figure out.)
You can only import a module from other modules, because import
is a modules feature.
How did you 'import' before ES6 modules? You didn't, because it didn't exist. You can actually interact with an E6 Module the same was as you used interact between two independent non-module scripts.
Hold and drag the module file into the chrome dev console.
Be sure to drag it to the input line section (after >
) of the console.
(This works on my Chrome 78 under Windows 10.)
this worked for me in node.js 12.12.0
using typescript
:
in my main.ts
I import wtfnode and set it on the global namesapace:
import * as wtf from 'wtfnode';
(global as any).wtfm = wtf;
in the Debugger console, I can now access wtfm
:
wtfm.init();
wtfm.dump();