'Detect whether an npm package can run on browser, node or both

I'm building a NextJs application which uses a set of abstractions to enable code from both react (Component logic etc.) and node (API logic) to utilize same types and classes. The motive here is to make the development process seem seamless across client side and server side.

For example. a call on User.create method of the User class will behave differently based on the runtime environment (ie. browser or node) - on the browser, it will call an api with a POST request and on server it will persist data to a database.

So far this pattern worked just fine, and I like how it all turned out in terms of the code structure. However, for this to work, I have to import modules responsible for working on the server and browser to a single module (which in this case is the User class) this leads to a critical error when trying to resolve dependencies in each module.

For example I'm using firebase-admin in the server to persist data to the Firebase Firestore. But it uses fs which cannot be resolved when the same code runs on the browser.

As a work around I set the resolve alias of firebase-admin to false inside the webpack configuration (given it runs on browser) see code below.

/** next.config.js **/
webpack: (config, { isServer }) => {
if (!isServer) {
    // set alias of node specific modules to false
    // eg: service dependencies
    config.resolve.alias = {
        ...config.resolve.alias,
        'firebase-admin': false,
    }
} else {
  // set alias of browser only modules to false.
    config.resolve.alias = {
      ...config.resolve.alias,
    }
}

While this does the trick, it won't be much long until the process gets really tedious to include all such dependencies within resolve aliases.

So, my approach to this is to write a script that runs prior to npm run dev (or manually) that will read all dependencies in package.json and SOMEHOW identify packages that will not run on a specific runtime environment and add them to the webpack config. In order to this, there should be a way to identify this nature of each dependency which I don't think is something that comes right out of the box from npm or the package itself.

Any suggestion on how this can be achieved is really appreciated. Thanks`



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source