How do you use resolve.alias in webpack?

webpack has an option called resolve which can help prevent some gnarly errors in packages like React and GraphQL.

What happens is, some packages choose to include common packages as dependencies rather than as peer dependencies. Net result is that your bundle ends up larger, or in the case of React or GraphQL packages, you get random errors.

In React, having more than one version of React in your dependencies can cause this common error: hooks can only be called inside the body of a function component.

Luckily for us, the fix is pretty simple - we add the following to our webpack config:

 resolve: {
    alias: {
      react: path.dirname(require.resolve('react')),
    },
  }

Enjoyed this post? Receive the next one in your inbox!