I don't understand how webpack's require
function work. For example, I'm reading this article about webpack and there is the following example:
Let's start by creating our project and installing Webpack, we'll also pull in jQuery to demonstrate some things later on.
$ npm init
$ npm install jquery --save
$ npm install webpack --save-dev
Now let's create our app's entry point, in plain ES5 for now:
src/index.js
var $ = require('jquery');
$('body').html('Hello');
And let's create our Webpack configuration, in a webpack.config.js file. Webpack configuration is just Javascript, and needs to export an object:
webpack.config.js
module.exports = {
entry: './src',
output: {
path: 'builds',
filename: 'bundle.js',
},
};
How does webpack know what is jquery in require('jquery')
? I don't see any configuration options specified related to jquery.
WebPack is basically a packer of modules or module bundler, but thanks to one of its components, the plugins, can be used as tasks runner, ie we can do tasks of all kinds, such as moving directories, clean up, etc... To understand what Webpack is, let's analyze this graph a bit.
If dependencies are not provided, factoryMethod is called with require, exports and module (for compatibility!). If this function returns a value, this value is exported by the module. The compiler ensures that each dependency is available. Note that webpack ignores the name argument.
Here, starts the function declaration of __webpack_require__. It takes moduleId as parameter and whenever this function is invoked then the cache is being checked if the module is already loaded or not. If yes then module is returned from the cache else we load the module.
While webpack supports multiple module syntaxes, we recommend following a single syntax for consistency and to avoid odd behaviors/bugs. Actually webpack would enforce the recommendation for .mjs files, .cjs files or .js files when their nearest parent package.json file contains a "type" field with a value of either "module" or "commonjs".
In this case, it's going to work just like CommonJS require
s (e.g., Node require
s). (Webpack's require
s support more flexibility than traditional require
s, but the default behavior is the same.)
This Modules section in the docs explains how Node figures out what to return from a call to require()
. If you require 'jquery', it first looks for a native module of that name, doesn't find one, and then looks in node_modules
(because there's no /
or ./
at the beginning of your path). Since 'jquery' is a folder, it looks at the package.json
file to see what it declares the main
file of the package to be, and that's what it executes.
It's worth reading the whole thing; the caching part, for example, is important to know.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With