Search code examples
javascriptreactjswebpackreact-hooksbundle

Custom react hook library. Webpack externals and peerDependencies doesn't work


Each new try I getting 2 cases:

"Invalid hook call" - because of double React environment.

"Can't resolve "react"" - if I would remove it from devDependencies in hook library.

Goal is : to set up correct build environment of hook library.

webpack.config.js

const path = require("path")

module.exports = {
    mode: "production",
    entry: "./src/index.ts",
    output: {
        filename: "index.js",
        path: path.resolve(__dirname, 'dist'),
        clean: true,
        library: "custom-hook-lib",
        libraryTarget: "umd"
    },
    externals: {
        'react': 'react',
        'react-dom' : 'reactDOM'
    },

    resolve: {
        extensions: [".js", ".jsx", ".json", ".ts", ".tsx"]
    },
    
    module: {
        rules: [
            {
                test: /\.(j|t)sx?$/,
                exclude: /(node_modules)/,
                use: 'ts-loader'
            }
        ]        
    }
    
}

package.json

{
  "name": "custom-hook-lib",
  "version": "1.0.0",
  "description": "",
  "main": "dist/index.js",
  "module": "dist/index.js",
  "files": [
    "dist"
  ],
  "keywords": [],
  "license": "ISC",
  "peerDependencies": {
    "react": "^18.2.0",
    "react-dom": "^18.2.0"
  },
  "devDependencies": {
    "react": "^18.2.0",
    "react-dom": "^18.2.0",
    "@types/react": "^18.0.17",
    "typescript": "^4.8.2",
    "webpack": "^5.74.0",
    "webpack-cli": "^4.10.0",
    "ts-loader": "^9.3.1"
  }
}



Solution

  • After a few days of investigation I can answer:

    There is wasn't building issue. I tried tsc, rollup, webpack. I tried to steal already working libs build configuration. Tried create-react-library. And after that I just get know from this Video, that for the testing you can't use npm/yarn link or just local path if there is hook in your project

    You should build and publish your React library that's using hooks to test.