Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

require a module with webpack

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

like image 237
Frédéric GRATI Avatar asked Apr 29 '14 13:04

Frédéric GRATI


People also ask

Can you use require with webpack?

Each time you use the AMD-style require([]) or require. ensure() webpack will see what you passed in there and go and create a bundle with every possible match. That works great if you pass in a single file, but when you use a variable, it might end up bundling your entire view folder.

What is a module in webpack?

Webpack is an aggressive and powerful module bundler for JavaScript applications. It packages all the modules in your application into one or more bundles (often, just one) and serves it to the browser. However, Webpack is more than just a module bundler.

What is module rules in webpack?

module. rules allows you to specify several loaders within your webpack configuration. This is a concise way to display loaders, and helps to maintain clean code.


1 Answers

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.

like image 126
matpie Avatar answered Oct 16 '22 12:10

matpie