0

I am trying to make an external component library. I am using Webpack and TypeScript. Compiles fine but when trying to use the library I get:

Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons: 1. You might have mismatching versions of React and the renderer (such as React DOM) 2. You might be breaking the Rules of Hooks 3. You might have more than one copy of React in the same app See /react-invalid-hook-call for tips about how to debug and fix this problem.

Which sounds like webpack bundled React rather than respecting it being a peer dependency. Upon inspecting the bundled file, I can see hints of React's source code.

How do I prevent React from being bundled? Here's the repo of the library

https://github.com/alshdavid-sandbox/react-component-lib-problem

Right now my webpack config looks like:

module.exports = {
    entry: path.join(__dirname, '/src/index.ts'),
    mode,
    output: {
        filename: 'index.js',
        publicPath: '',
        path: path.join(__dirname, 'build'),
        libraryTarget: 'commonjs'   
    },
    module: {
        rules: [
            {
                test: /\.tsx?$/,
                loader: 'ts-loader',
                exclude: /node_modules/,
            }
        ]
    },
    resolve: {
        extensions: [".tsx", ".ts", ".js"],
    },
};
1
  • Do you need react-dom too? Ex. react-redux has both react and react-dom Commented Aug 9, 2019 at 3:46

1 Answer 1

1

I had to add the following to my webpack config

externals: {      
    react: {          
        commonjs: "react",          
        commonjs2: "react",          
        amd: "React",          
        root: "React"      
    },      
    "react-dom": {          
        commonjs: "react-dom",          
        commonjs2: "react-dom",          
        amd: "ReactDOM",          
        root: "ReactDOM"      
    }  
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.