Alexander Solonik
Alexander Solonik

Reputation: 10230

How does webpack pick a relative path inside node_modules ? does it reference package.json at all?

When i do npm install react-slick, i get the following in my node_modules folder:

enter image description here

Now in my react application in a src/index.js file, when i do the following:

import Slider from "react-slick";

How does webpack know where to pick slider from ? will it at all look for some clue or definition inside node_modules/react-slick/package.json at all ?

Edit :- so here is the package.json file for webpack, when i import Slider from 'react-slick' , does it resolve to dist or lib ? and which file does it pick then and why ?

Upvotes: 1

Views: 1870

Answers (2)

SMAKSS
SMAKSS

Reputation: 10520

Well, the simple walkthrough of it will be as below:

Simple Walkthrough

If you carefully look at the node_modules/react-slick/package.json there is a property named main. Something like this:

{
  "name": "react-slick",
  "main": "index.js"
}

It will tell the Webpack which file is the entry file of the whole package (It's usually referred to index.js). All the necessary exports for the package lies in this file, so Webpack will only look for those exports and will import what you looking for. In this particular case, there should be a default export for the Slider that you using right now. So the index.js is probably something like this:

// index.js
var slider = require('./lib/slider'); // Usually all the main modules are lies under lib folder.
// other imports ...
module.exports = slider;

Difference between lib and dist

Usually, the dist folder is for shipping a UMD that a user can use if they aren't using package management. The lib folder is what package.json, main property points to, and users that install your package using npm will consume that directly. The only use of the lib as opposed to src is to transform your source using babel and Webpack to be more generally compatible since most build processes don't run babel transforms on packages in node_modules.

Upvotes: 3

Antonio Erdeljac
Antonio Erdeljac

Reputation: 3244

Webpack uses aliases to target node_modules using a shorthand.

Example #1:

import 'xyz'
/abc/node_modules/xyz/index.js

Example #2:

import 'xyz/file.js'
/abc/node_modules/xyz/file.js

Once it targets the correct folder in node_modules, it follows the rules written in the package itself (manifest, package.json)

You can also define your own aliases as such:

webpack.config.js

const path = require('path');
module.exports = {
  //...
  resolve: {
    alias: {
      xyz$: path.resolve(__dirname, 'path/to/file.js')
    }
  }
};

And then can be used as import xyz from $xyz

Upvotes: 1

Related Questions