如何在我的组件库中使用 React hooks?

How do I use React hooks in my component library?

我目前正在创建一个组件库,它通过 NPM link 包含在 Nextjs 项目中,并且很难让它始终如一地加载而不会出错。最新的是

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

这是一个 Typescript 组件,但据我所知,我所做的还可以,但不是在玩游戏。这是代码:

        import React, { useEffect } from "react";
        import { FlagIcon } from "react-flag-kit";

        const LanguageSwitcher = () => {
            useEffect(() => {
                alert('Yo!');
            })
            return (
                <div className="w-full justify-end">
                    <button>
                        <div className="flex items-center">
                            <FlagIcon code="GB" /> <span className="block ml-2">English</span>
                        </div>
                    </button>
                </div>
            )
        }

        export default LanguageSwitcher

然后将其导入到库中的另一个组件中,然后导入到 Nextjs 页面中。这就是错误出现的地方。

我不确定这是 webpack 还是 typescript 编译问题,尝试了所有我能想到的不同目标,尝试了谷歌搜索各种东西,但似乎没有什么与我的情况相关。它甚至可能不是 React 的问题,而是 Typescript 和 Webpack 的问题,但我对它们的接触是非常新的。

我的 webpack 配置:

        var path = require('path');
        module.exports = {
          entry: './src/index.ts',
          devtool: "source-map",
          output: {
            path: path.resolve(__dirname, 'build'),
            filename: 'index.js',
            libraryTarget: 'commonjs2'
          },
          module: {
            rules: [
              {
                test: /\.ts(x?)$/,
                use: 'ts-loader',
                exclude: /node_modules/,
              },
              {
                enforce: "pre",
                test: /\.js$/,
                loader: "source-map-loader"
              }
            ]
          },
          resolve: {
            extensions: [ '.tsx', '.ts', '.js' ],
          }
        };

我的tsconfig.json


    {
      "compilerOptions": {
        "outDir": "build",
        "module": "esnext",
        "target": "es6",
        "lib": ["es6", "dom", "es2016", "es2017"],
        "sourceMap": true,
        "allowJs": false,
        "jsx": "react",
        "declaration": true,
        "moduleResolution": "node",
        "forceConsistentCasingInFileNames": true,
        "noImplicitReturns": true,
        "noImplicitThis": true,
        "noImplicitAny": true,
        "strictNullChecks": true,
        "suppressImplicitAnyIndexErrors": true,
        "noUnusedLocals": true,
        "noUnusedParameters": true,
        "allowSyntheticDefaultImports": true
      },
      "include": ["src"],
      "exclude": ["node_modules", "build"]
    }

非常感谢任何指点或帮助!

我也试过将所有内容还原为普通 JS,但问题仍然存在,所以我认为这可能与 webpack 相关?

编辑

这是我的完整 package.json 文件以及 Nextjs 的内容

{
  "name": "some/package",
  "version": "1.0.0",
  "description": "",
  "main": "build/index.js",
  "scripts": {
    "test": "jest",
    "start": "webpack --watch --mode=development",
    "build": "webpack"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "react": "16.10.2",
    "webpack": "^4.41.1"
  },
  "devDependencies": {
    // ...
    "@types/react": "^16.9.5",
    "@types/react-dom": "^16.9.1",
    "react": "16.10.2",
    "react-dom": "^16.10.2",
    "ts-loader": "^6.2.0",
    "typescript": "^3.6.4",
    "webpack-cli": "^3.3.9"
  }
}
    "react": "16.10.2",
    "react-dom": "16.10.2"

原来这是由于组件库中的 symlinked 反应问题

https://reactjs.org/warnings/invalid-hook-call-warning.html#duplicate-react

已通过 运行 link 中的步骤修复:

npm link ../myapp/node_modules/react // Run within the component library

遇到了同样的问题。但是,组件库不归我所有,因此不得不使用这个 dependency resolution by 'Yarn'

这是我最初的依赖关系树

project
|- componentLibrary
|  |- react@16.10
|  |- react-dom@16.10
|- react@17.0.1
|- react-dom@17.0.1

在我的 package.json

中添加了以下片段
"resolutions": {
  "componentLibrary/react": "17.0.1",
  "componentLibrary/react-dom": "17.0.1"
},

这解决了我对项目 reactreact-dom 的依赖关系。