How to depend on an optional native module without breaking webpack users?

322 Views Asked by At

I maintain a npm module that is used in node and the browser, with and without webpack. I want to add an optional feature that relies on a native module without breaking or requiring changes from our webpack users.

The native module is optional

"optionalDependencies": {
  "feature-module": "^1.0.0",
}

I require it in a try/catch

module.export = function doThing() {
  try {
    require('feature-module');
  } catch (err) {
    // fallack without feature
  }
}

This is pretty similar to the example in package.json documentation.

It works okay outside webpack and even in webpack when the optional dependencies is not installed.

However when the optional module is installed webpack tries to require it and errors because it doesn't have a loader for the files it finds.

ERROR in ./node_modules/my-package/node_modules/feature-module/build/Release/feature-module.node 1:0
Module parse failed: Unexpected character '' (1:0)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
(Source code omitted for this binary file)
@ ./node_modules/my-package/node_modules/feature-module/index.js
@ ./node_modules/my-package/index.js
1

There are 1 best solutions below

2
On

You can describe it in your package.json

{
  ...

  "browser": { "feature-module": false },

  ...
}

This is how I fixed such issue for txml. (github/txml/package.json).