Reputation: 105497
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.
Upvotes: 11
Views: 14077
Reputation: 2652
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.
Upvotes: 11