Home > OS >  Npm package with React hooks
Npm package with React hooks

Time:06-07

I have been working on my own UI lib. But I found a problem. Looks like that many developers have same problem, but I can't find any solution.

For demonstration purposes I created very simple example.

Npm package

// index.js
export { default as NoHook } from './components/NoHook'
export { default as WithHook } from './components/WithHook'
// NoHook.js
import React from 'react'
const NoHook = () => {
    return (
        <div>NoHook</div>
    )
}
export default NoHook
// WithHook.js
import React, { useEffect } from 'react'
const WithHook = () => {
    useEffect(() => {
        console.log("log")
    }, [])
    return (
        <div>WithHook</div>
    )
}
export default WithHook
// webpack.config.js
var path = require("path")

module.exports = {
    mode: "production",
    entry: "./src/index.js",
    output: {
        path: path.resolve("build"),
        filename: "index.js",
        libraryTarget: "commonjs2"
    },
    module: {
        rules: [
            {
                test: /\.(js|jsx)$/,
                exclude: /nodeModules/,
                use: {
                    loader: "babel-loader"
                }
            }
        ]
    }
}
// package.json
{
  "name": "hookpackage",
  "version": "1.0.0",
  "description": "",
  "main": "./build/index.js",
  "scripts": {
    "build": "webpack"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "react": "^17.0.2",
    "react-dom": "^17.0.2"
  },
  "devDependencies": {
    "@babel/core": "^7.14.6",
    "@babel/preset-env": "^7.14.7",
    "@babel/preset-react": "^7.14.5",
    "babel-loader": "^8.2.2",
    "webpack": "^5.40.0",
    "webpack-cli": "^4.7.2"
  }
}

In some random app, which import my NPM package

import React from 'react'
import { NoHook, WithHook }from 'hookpackage'
const App = () => {
  return (
    <>
      <NoHook />
      <WithHook />
    </>
  )
}
export default App

Error

Invalid hook call. Hooks can only be called inside of the body of a function component ...

I already tried put dependencies into peerDependencies, but it doesn't work.

CodePudding user response:

Add this to webpack solved it.

 externals: {
    react: {
        root: 'React',
        commonjs2: 'react',
        commonjs: 'react',
        amd: 'react'
    },
    'react-dom': {
        root: 'ReactDOM',
        commonjs2: 'react-dom',
        commonjs: 'react-dom',
        amd: 'react-dom'
    }
  }

CodePudding user response:

My guess is the libraryTarget property in your webpack configuration file. Try umd

https://webpack.js.org/configuration/output/#librarytarget-commonjs2

  • Related