6.1.2: Webpack with NPM Modules


​Module 6.1.1: Webpack with Local Modules shared how Webpack can compile local modules into a distribution file. Here we will see how Webpack compiles 3rd-party NPM modules.

Webpack Import with NPM Modules Order of Events

Webpack will transform the source JS file and all dependencies specified in import statements into a single distribution file.
  1. 1.
    npm install is run on the command line. The package files are stored in the node_modules directory.
  2. 2.
    The webpack command is run on the command line.
  3. 3.
    Webpack reads an import statement in the source script.js file.
  4. 4.
    Based on the import, Webpack retrieves all dependency code. If the imported module depends on other modules, Webpack retrieves those modules too.
  5. 5.
    Webpack writes the compiled file into the dist directory.
  6. 6.
    The server is started with node index.js. A request is made to the server. The server responds with the compiled JS file in dist.

Webpack Import with NPM Modules Example

Begin with the same repo created in the previous section, 6.1.1: Webpack with Local Modules
Install the npm package, cat-names by running the command npm install cat-names in the terminal
npm install cat-names
Next, in ./src/index.js, import cat-names (line 3), and use the package (line 5).
import { cat } from './cat.js';
import { mouse } from './mouse.js';
import catNames from 'cat-names';
console.log('cat', cat);
console.log('mouse', mouse);
Run the command npx webpack and look in ./dist/main.js to see the how webpack has processed the package.
Not all packages can be compiled by Webpack. Try installing pg, importing pg in src/script.js, and re-running Webpack.