What exactly is a "webpack module" in webpack's terminology?

Viewed 119

I am a newbie to webpack and currently trying to understand basic concepts. Looking at the official docs, on the page Concepts it uses module term and gives link to read more about modules on page Modules.

So on this page we have question "What is a module" but no explicit answer to that is given. Rather, it describes modules by how they "express their dependencies":

What is a webpack Module

In contrast to Node.js modules, webpack modules can express their dependencies in a variety of ways. A few examples are:

  • An ES2015 import statement

  • A CommonJS require() statement

  • An AMD define and require statement

  • An @import statement inside of a css/sass/less file.

  • An image url in a stylesheet url(...) or HTML file.

So it doesn't explicitly defines what exactly is the module and I am confused now.

Is module just a javascript file? Or is it any type of file like .css or images? Or is module some logical concept not related to physical files at all?

1 Answers

The simple answer to your question is that a Webpack Module is a Javascript file that is processed by Webpack.

As for why that's a thing, well, consider the following Javascript:

if (window.matchMedia('(max-width: 600px)')) {
  const img = document.querySelector('#header-responsive-image');
  img.src = 'different/image/url/file.jpg';
  img.classList.add('some-class');
}

Note that this code has dependencies on specific markup, image files, and CSS rules. But crucially you have to read the code to find out what they are. There's no (easy) way to statically analyze the dependencies (or even do it by hand!).

This may not seem like a big deal in small apps, but when you're working with a large Javascript codebase or authoring a component library, the ability to statically analyze the real dependency graph and have your tools warn you immediately when your JS, CSS, markup, and files on disk get out of sync is a lifesaver.

With Webpack at the top of the file you're going to see something more like this:

import header600Width from '../img/header-600-width.jpg';
import '../styles/has-some-class.css';
// etc.

You can load images, csv, xml, toml, json, css, and the list goes on. This is something that other modules systems by-and-large can't or won't do. So a Webpack module is, in a sense, a superset of a Javascript module.

Related