Skip to content

Node.js core modules polyfill #151

@nighca

Description

@nighca

Problem

Automatic Node.js polyfill is removed in Webpack v5. See details here. These solutions is recommended:

  1. Try to use frontend-compatible modules whenever possible.
  2. It's possible to manually add a polyfill for a Node.js core module. An error message will give a hint on how to achieve that.
  3. Package authors: Use the browser field in package.json to make a package frontend-compatible. Provide alternative implementations/dependencies for the browser.

If you use webpack directly, you can do the 2nd thing like this:

// webpack config
module.exports = {
  resolve: {
    fallback: {
      "crypto": require.resolve("crypto-browserify"),
      "stream": require.resolve("stream-browserify"),
      // ...
    }
  },
}

However there is no way to specify resolve.fallback when using builder. Which means, currently there is no way to do Node.js core module polyfill for builder users. This is the problem.

Proposal

We can add a field in build config optimization:

{
  "optimization": {
    "addNodePolyfill": ["crypto"]
  }
}

No module will be polyfilled by default. If you specify module names in the list, builder will find the proper polyfill and do the resolve fallback work.

Notice that it is not easy to do the above work, cause the proper polyfill packages is a messy and there are hacks in resolve fallback configuration, such as

require.resolve("assert/")

instead of

require.resolve("assert"),

There is a plugin doing these for us, we can implement polyfillNode based on it.

Related links

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions