How do I require() / import modules from the console? For example, say I've installed the ImmutableJS npm, I'd like to be able to use functions from the module while I'm working in the console.
-
1The accepted answer doesn't work anymore. Please check an updated answer: https://stackoverflow.com/a/70600070/3317037 – daymannovaes Jan 05 '22 at 21:58
10 Answers
Here's another more generic way of doing this.
Requiring a module by ID
The current version of WebPack exposes webpackJsonp(...)
, which can be used to require a module by ID:
function _requireById(id) {
return webpackJsonp([], null, [id]);
}
or in TypeScript
window['_requireById'] =
(id: number): any => window['webpackJsonp'];([], null, [id]);
The ID is visible at the top of the module in the bundled file or in the footer of the original source file served via source maps.
Requiring a module by name
Requiring a module by name is much trickier, as WebPack doesn't appear to keep any reference to the module path once it has processed all the sources. But the following code seems to do the trick in lot of the cases:
/**
* Returns a promise that resolves to the result of a case-sensitive search
* for a module or one of its exports. `makeGlobal` can be set to true
* or to the name of the window property it should be saved as.
* Example usage:
* _requireByName('jQuery', '$');
* _requireByName('Observable', true)´;
*/
window['_requireByName'] =
(name: string, makeGlobal?: (string|boolean)): Promise<any> =>
getAllModules()
.then((modules) => {
let returnMember;
let module = _.find<any, any>(modules, (module) => {
if (_.isObject(module.exports) && name in module.exports) {
returnMember = true;
return true;
} else if (_.isFunction(module.exports) &&
module.exports.name === name) {
return true;
}
});
if (module) {
module = returnMember ? module.exports[name] : module.exports;
if (makeGlobal) {
const moduleName = makeGlobal === true ? name : makeGlobal as string;
window[moduleName] = module;
console.log(`Module or module export saved as 'window.${moduleName}':`,
module);
} else {
console.log(`Module or module export 'name' found:`, module);
}
return module;
}
console.warn(`Module or module export '${name}'' could not be found`);
return null;
});
// Returns promise that resolves to all installed modules
function getAllModules() {
return new Promise((resolve) => {
const id = _.uniqueId('fakeModule_');
window['webpackJsonp'](
[],
{[id]: function(module, exports, __webpack_require__) {
resolve(__webpack_require__.c);
}},
[id]
);
});
}
This is quick first shot at this, so it's all up for improvement!

- 2,003
- 16
- 17
-
Nice! For me it is able to retrieve all the modules in the bundle. However, it only worked when I set the id be to 0: `const id = 0;`. When I used the code above (and some other strings/numbers), the promise never resolved. – Venryx Mar 27 '17 at 17:55
-
3Doesn't work for me: `window.webpackJsonp is not a function` :( Anything I should require? – Septagram Jun 22 '17 at 17:54
-
@Septagram webpackJsonp only gets included on the page when you load some chunk. One trick I found is to use the CommonChunksPlugin and only pass it your main(assuming thats all you have), then you'll end up with the webpackRuntime and your bundle seperated, and you include them both on the page(or htmlplugin does it for you) – light24bulbs Dec 19 '17 at 20:45
-
1Where is `webpackJsonp()` defined and what are its arguments? Cannot find anywhere in webpack's source code. – cprcrack Jul 16 '18 at 19:57
-
YOur solution doesn't work anymore. Please check my solution: https://stackoverflow.com/a/70600070/3317037 – daymannovaes Jan 05 '22 at 21:57
Including this in a module will allow require([modules], function)
to be used from a browser
window['require'] = function(modules, callback) {
var modulesToRequire = modules.forEach(function(module) {
switch(module) {
case 'immutable': return require('immutable');
case 'jquery': return require('jquery');
}
})
callback.apply(this, modulesToRequire);
}
Example Usage:
require(['jquery', 'immutable'], function($, immutable) {
// immutable and $ are defined here
});
Note: Each switch-statement option should either be something this module already requires, or provided by ProvidePlugin
Sources:
Based on this answer, which can be used to add an entire folder.
Alternative method from Webpack Docs - which allows something like require.yourModule.function()
-
Is it possible to `require` something into the top level context using this method? – amoe Apr 19 '16 at 14:21
I found a way that works, for both WebPack 1 and 2. (as long as the source is non-minified)
Repo: https://github.com/Venryx/webpack-runtime-require
Install
npm install --save webpack-runtime-require
Usage
First, require the module at least once.
import "webpack-runtime-require";
It will then add a Require() function to the window object, for use in the console, or anywhere in your code.
Then just use it, like so:
let React = Require("react");
console.log("Retrieved React.Component: " + React.Component);
It's not very pretty (it uses regexes to search the module wrapper functions) or fast (takes ~50ms the first call, and ~0ms after), but both of these are perfectly fine if it's just for hack-testing in the console.
Technique
The below is a trimmed version of the source to show how it works. (see the repo for the full/latest)
var WebpackData;
webpackJsonp([],
{123456: function(module, exports, __webpack_require__) {
WebpackData = __webpack_require__;
}},
[123456]
);
var allModulesText;
var moduleIDs = {};
function GetIDForModule(name) {
if (allModulesText == null) {
let moduleWrapperFuncs = Object.keys(WebpackData.m).map(moduleID=>WebpackData.m[moduleID]);
allModulesText = moduleWrapperFuncs.map(a=>a.toString()).join("\n\n\n");
// these are examples of before and after webpack's transformation: (which the regex below finds the var-name of)
// require("react-redux-firebase") => var _reactReduxFirebase = __webpack_require__(100);
// require("./Source/MyComponent") => var _MyComponent = __webpack_require__(200);
let regex = /var ([a-zA-Z_]+) = __webpack_require__\(([0-9]+)\)/g;
let matches = [];
let match;
while (match = regex.exec(allModulesText))
matches.push(match);
for (let [_, varName, id] of matches) {
// these are examples of before and after the below regex's transformation:
// _reactReduxFirebase => react-redux-firebase
// _MyComponent => my-component
// _MyComponent_New => my-component-new
// _JSONHelper => json-helper
let moduleName = varName
.replace(/^_/g, "") // remove starting "_"
.replace(new RegExp( // convert chars where:
"([^_])" // is preceded by a non-underscore char
+ "[A-Z]" // is a capital-letter
+ "([^A-Z_])", // is followed by a non-capital-letter, non-underscore char
"g"),
str=>str[0] + "-" + str[1] + str[2] // to: "-" + char
)
.replace(/_/g, "-") // convert all "_" to "-"
.toLowerCase(); // convert all letters to lowercase
moduleIDs[moduleName] = parseInt(id);
}
}
return moduleIDs[name];
}
function Require(name) {
let id = GetIDForModule(name);
return WebpackData.c[id].exports;
}

- 15,624
- 10
- 70
- 96
Being able to use require
modules in the console is handy for debugging and code analysis. @psimyn's answer is very specific so you aren't likely to maintain that function with all the modules you might need.
When I need one of my own modules for this purpose, I assign a window property to it so I can get at it e.g window.mymodule = whatever_im_exporting;
. I use the same trick to expose a system module if I want to play with it e.g:
myservice.js:
let $ = require('jquery');
let myService = {};
// local functions service props etc...
module.exports = myService;
// todo: remove these window prop assignments when done playing in console
window.$ = $;
window.myService = myService;
It is still a bit of a pain, but digging into the bundles, I can't see any way to conveniently map over modules.

- 1
- 1

- 16,028
- 4
- 42
- 54
-
1This is a bad practice. Everytime I have done something like this I have regretted it. – Aluan Haddad Aug 12 '16 at 21:27
-
1@AluanHaddad: Can you explain? This is purely to interactively experiment and test things as you go. I do find it very useful being able to interact with my services to "poke" them and verify that they behave as expected. – Paul Whipp Aug 15 '16 at 18:51
-
What I mean is that it's very very easy to forget to remove the code. I've forgotten to do it before and I'm sure many other people have as well. – Aluan Haddad Aug 17 '16 at 22:03
-
-
1@AluanHaddad, I feel it similar. On the other hand if you have set up good TODO management, it could be okay. We have simple rule: "No TODOs when releasing." ;) – Milan Jaros Apr 12 '17 at 08:32
-
@MilanJaros prthaps true, but I can't even get some of my coworkers to run the linter, so YMMV with `// TODO: remove this`. One of the reasons I prefer loaders to packagers is that you can do experiments like this without changing code, just using a browser console. `SystemJS.import('lodash').then(({default}) => window._ = default);`. I know this question is about Webpack, I'm just ranting, and you have to admit that's pretty nice. – Aluan Haddad Apr 12 '17 at 08:42
-
@AluanHaddad, I admit, indeed. :) Have you realized that you can create different webpack config for development and for release? Release should be completely without such "devDependencies". – Milan Jaros Apr 18 '17 at 21:20
-
@MilanJaros most definitely although typically released configuration will just contain optimizations and different env config. `devdependencies`, aside from debugging utils, are mostly tools that would not be in any bundle. If you are suggesting providing certain dependencies as globals in development bundles but as modules in production bundles, that sounds quite dangerous. An unfortunate number of implicit global dependencies exist between client-side packages. – Aluan Haddad Apr 19 '17 at 01:06
-
I often wrap the dev code in `if (process.env.NODE_ENV !== 'production'){...}` to avoid any potential trouble on deployment. – Paul Whipp Apr 19 '17 at 01:32
-
@PaulWhipp is that block mutates global state by assigning libs to window it's likely to cause an implicit dependency. Most obvious example are little jQuery plugins that are badly written (don't check for `define`, `require`/`exports`) – Aluan Haddad Apr 20 '17 at 02:53
The answer from @Rene Hamburger is good but unfortunately doesn't work anymore (at least with my webpack version). So I updated it:
function getWebpackInternals() {
return new Promise((resolve) => {
const id = 'fakeId' + Math.random();
window['webpackJsonp'].push(["web", {
[id]: function(module, __webpack_exports__, __webpack_require__) {
resolve([module, __webpack_exports__, __webpack_require__])
}
},[[id]]]);
});
}
function getModuleByExportName(moduleName) {
return getWebpackInternals().then(([_, __webpack_exports__, __webpack_require__]) => {
const modules = __webpack_require__.c;
const moduleFound = Object.values(modules).find(module => {
if (module && module.exports && module.exports[moduleName]) return true;
});
if (!moduleFound) {
console.log('couldnt find module ' + moduleName);
return;
}
return moduleFound.exports[moduleName];
})
}
getModuleByExportName('ExportedClassOfModule');

- 1,416
- 12
- 23
expose-loader is, in my opinion, a more elegant solution:
require("expose-loader?libraryName!./file.js");
// Exposes the exports for file.js to the global context on property "libraryName".
// In web browsers, window.libraryName is then available.

- 320
- 3
- 6
-
It's a disadvantage that the each module is exposed as a global name though. Increases chances that the dev-bulid behaves different from the production build. (assuming the exposing is strictly ment for dev convenience) (could use some _dev prefix ofc.) – olejorgenb Nov 25 '19 at 16:52
Adding the below code to one of your modules will allow you to load modules by id.
window.require = __webpack_require__;
In the console use the following:
require(34)

- 3,030
- 2
- 16
- 18
-
1Is there a quick way yo understand what number does my module have? – Eugene Tiutiunnyk Oct 11 '17 at 19:38
-
@eugenet8k The webpack output should have labels on modules. For the above example I would have seen /* 34 */ in the output file. Let me know if this helps. – lcharbon Oct 11 '17 at 20:46
You could do something similar as psimyn advised by adding following code to some module in bundle:
require.ensure([], function () {
window.require = function (module) {
return require(module);
};
});
Use require from console:
require("./app").doSomething();

- 1
- 1

- 1,107
- 17
- 24
-
Did you actually try this? Doesn't seem to work. Just returned undefined. Probably because webpack has to know the module name at compile time (I believe); it shows this error during compile with the above: "WARNING in [...] Critical dependencies: [...] the request of a dependency is an expression" – Venryx Mar 27 '17 at 17:59
-
Sure, I did. We used it for a while to experiment with custom services. If you'd find it helpful I could try to cut out the example from the project. Please note, that finally we ended up with a way similar to http://stackoverflow.com/a/38214280/164680. Similar? I mean that we had different config for debug and release. – Milan Jaros Apr 18 '17 at 21:16
-
That's all-right, I found/made [another way](http://stackoverflow.com/a/43055806/2441655). Thanks though. – Venryx Apr 18 '17 at 23:05
After making an npm module for this (see my other answer), I did a search on npms.io and seem to have found an existing webpack-plugin available for this purpose.
Repo: https://www.npmjs.com/package/webpack-expose-require-plugin
Install
npm install --save webpack-expose-require-plugin
Usage
Add the plugin to your webpack config, then use at runtime like so:
let MyComponent = require.main("./path/to/MyComponent");
console.log("Retrieved MyComponent: " + MyComponent);
See package/repo readme page for more info.
EDIT
I tried the plugin out in my own project, but couldn't get it to work; I kept getting the error: Cannot read property 'resource' of undefined
. I'll leave it here in case it works for other people, though. (I'm currently using the solution mentioned above instead)
After both making my own npm package for this (see here), as well as finding an existing one (see here), I also found a way to do it in one-line just using the built-in webpack functions.
It uses WebPack "contexts": https://webpack.github.io/docs/context.html
Just add the following line to a file directly in your "Source" folder:
window.Require = require.context("./", true, /\.js$/);
Now you can use it (eg. in the console) like so:
let MyComponent = Require("./Path/To/MyComponent");
console.log("Retrieved MyComponent: " + MyComponent);
However, one important drawback of this approach, as compared to the two solutions mentioned above, is that it seems to not work for files in the node_modules folder. When the path is adjusted to "../", webpack fails to compile -- at least in my project. (perhaps because the node_modules folder is just so massive)