Search code examples
reactjsrollupjsreact-hookscodesandbox

Configuring rollup for a react library


I am sorry, I didn't where else to post this.

This is my rollup configuration

import resolve from 'rollup-plugin-node-resolve';
import commonjs from 'rollup-plugin-commonjs';
import babel from 'rollup-plugin-babel';
import { terser } from 'rollup-plugin-terser';
import pkg from './package.json';

export default {
  input: 'src/index.js',
  external: ['react', 'react-dom', 'prop-types'],
  output: [
    { file: pkg.main, format: 'cjs', exports: 'named' },
    { file: pkg.module, format: 'es', exports: 'named' },
  ],
  plugins: [
    resolve(),
    commonjs({
      include: 'node_modules/**',
    }),
    babel({
      exclude: 'node_modules/**',
    }),
    terser(),
  ],
};

Here is the entire source code of my project https://github.com/withvoid/melting-pot

It is published on npmjs https://www.npmjs.com/package/@withvoid/melting-pot

my problem is, my library works great if I add it in a https://github.com/facebook/create-react-app project, but when I add it in a codesandbox project

https://codesandbox.io/s/6lqzp7q28w

It gives me an error that

Invariant Violation Hooks can only be called inside the body of a function component.

I can't seem to figure out if this is a codesandbox issue (which I am doubtful of) or an issue with my rollup configuration.


Solution

  • The issue is that melting-pot has "react" and "react-dom" specified as dependencies, but they should be specified as peerDependencies. This is having the effect of pulling React in twice with ill effects. If I remove the react dependencies from the sandbox entirely, it works because then React is only being pulled in once (by melting-pot). Obviously this isn't the appropriate resolution, but it is a quick way to verify the cause of the error.