Webpack external OPTIONAL modules

743 Views Asked by At

Im working on a library that requires some optional peer dependencies.

  "peerDependencies": {
    "react-dnd": ">=14.0.0",
    "react-dnd-html5-backend": ">=14.0.0",
  },
  "peerDependenciesMeta": {
    "react-dnd": {
      "optional": true
    },
    "react-dnd-html5-backend": {
      "optional": true
    }
  },

The way I figure I could require them is

try {
  DndProvider = require('react-dnd').DndProvider;
  HTML5Backend = require('react-dnd-html5-backend').HTML5Backend;
} catch (err) {
  // optional module not installed
}

And I declared them as externals like this:

  externals: {
    "react-dnd": {
      commonjs2: 'react-dnd',
      commonjs: 'react-dnd',
      amd: 'react-dnd',
      root: 'react-dnd',
    },
    "react-dnd-html5-backend": {
      commonjs2: 'react-dnd-html5-backend',
      commonjs: 'react-dnd-html5-backend',
      amd: 'react-dnd-html5-backend',
      root: 'react-dnd',
    },
  }  

Now, this works but if forces the consumers to install the dependencies or else they will get a compiled with warnings Module not found: Error: Can't resolve 'react-dnd' messages

How can I tell webpack to not care if the module is not there?

I found that one way is to use __non_webpack_require__ but I feel discouraged after reading an answer here

1

There are 1 best solutions below

0
On

I don't think what you're looking for is possible. webpack will always fail if an imported module is missing.

To avoid sending the DnD library to the client if not used you could import it using a dynamic import in case some condition is met:

const dnd = await import('react-dnd')

Another option would be to create separate plugins with or without the dependencies.