1

I'm realizing that importing a module (for instance moment.js) that is internally used by third party module (ie a .vue component) gives a build where the module is redundant because imported twice.

Is this an expected behavior or I'm missing something ?

in package.json the version is absolutely the same if that matters.

Daniele
  • 829
  • 1
  • 13
  • 23

1 Answers1

0

The behavior is correct. In general, Webpack will walk over the tree of dependencies (included transitive dependencies i.e. dependencies of dependencies) of your application.

Also, webpack ensures that it packs the some dependency exactly once as long as all the imports leading to that dependency are resolved to a same file. This behavior changes only when:

  1. You have symbolic links (or shortcut links) in your code or node_modules.
  2. You have multiple versions of the same dependency.
  3. Accidental upper / lower case letter changes leads to a different file (Sometimes, it happens when code written on Windows which is case-insensitive is being built on Linux or vice a versa.)
  4. In rare case, if you are using dynamic imports, Webpack sometimes cannot figure out the exact dependencies.

You can use Webpack analyzer to figure out such anomalies in your bundle. Further, you can also use Webpack resolve functionality to guide the Webpack to never pack similar dependencies twice (which defer only by patch number or so).

Harshal Patil
  • 17,838
  • 14
  • 60
  • 126
  • The correct behavior is to resolve the two dependencies of same module even if one in the main repository and the other in a sub-module if they have the same path number (or same resolve logic). If I've understood well my dependencies are not well resolved (two times it imports the same dependency) Question, Is this still true even if the third party module exports in a pre-build format right ? – Daniele Jul 20 '21 at 13:43
  • If your third party module itself is using Webpack to package the library, then there is no way for Webpack to figure out that the module has been already included in pre-build and thus it ends up packaging the same module twice. In general, the third party module should exclude or use ES6 bundling and then ship it for other's consumption so that the application level bundler can properly figure out the transitive dependencies and avoid duplicates. – Harshal Patil Jul 21 '21 at 06:18