require a module with webpack

Frédéric GRATI picture Frédéric GRATI · Apr 29, 2014 · Viewed 8.5k times · Source

I use Webpack in order to build my javascript of my website.

Everything work perfectly but I would like to call require into a template (added dynamically).

I want to be able to require a module after the build. (require is not defined into the global context).

Is it possible ?

Thx

Answer

matpie picture matpie · Jul 3, 2014

An option which is available to you now is to create a context which you expose globally on window. I've had success using the following snippet:

// Create a `require` function in the global scope so that scripts that have
// not been webpack'd yet can still access them.
window["require"] = function (module) {
    return require("./public_modules/" + module + ".js");
}

Basically what you're doing is exposing a folder to webpack and telling it to pack all the files in that folder in to a chunk. You can then type var moduleName = require("module-name") outside of a webpack'd script.

As long as the above snippet is inside a file which gets bundled and evaluated, you will have a function defined on window (coincidentally named "require" but you can call it anything) which will use webpack's require functionality.