How to use ES6 modules from dev tools console

流过昼夜 提交于 2019-12-01 14:16:41

问题


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.


回答1:


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()



回答2:


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.)




回答3:


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.




回答4:


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.)



来源:https://stackoverflow.com/questions/52569996/how-to-use-es6-modules-from-dev-tools-console

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!