Skip to content

Avoid module duplicationΒ #1

Description

@m-sureshraj

If we require the same module in multiple places the bundler adds the same dependency multiple times into the bundle. Eg.

// main.js
const a = require('./a');
const b = require('./b');

// a.js
module.exports = () => {};

// b.js
const a = require('./a');

module.exports => () => { a(); };

The bundler will generate following dependency graph

main module <- a module <- b module <- a module

We can avoid this duplication by checking module existence in the graph. Inside the getModules function

module.requires.forEach(dependency => {
  const basedir = path.dirname(module.filepath)
  const dependencyPath = resolve(dependency, { basedir })

  // to avoid module duplication
  let dependencyObject = modules.find(m => m.filepath === dependencyPath);

  if (dependencyObject) {
    module.map[dependency] = dependencyObject.id
   } else {
    dependencyObject = createModuleObject(dependencyPath)
    module.map[dependency] = dependencyObject.id
    modules.push(dependencyObject)
  }
})

@adamisntdead I would like create a PR for the above changes, If you like this solution. Thanks.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions