我当前正在创建一个组件库,该组件库通过NPM链接包含在Nextjs项目中,并且很难使其始终如一地加载而不会出错。最新的是
无效的挂接调用。挂钩只能在功能组件的主体内部调用。可能由于以下原因之一而发生
这是一个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页面。错误在哪里显示。
I'm not sure if it's a webpack or typescript compiling issue, tried all the different targets I can think of, tried googling all sorts of things but nothing seems relevant to my situation. It might not even be a React issue but one with Typescript and Webpack, but my exposure to those is very new.
My webpack config:
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' ],
}
};
My 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"]
}
Any pointers or help would be really appreciated!
I also tried reverting everything back to vanilla JS and the problem persists, so I think it might be webpack related?
Edit
Here is my full package.json file and also what Nextjs has
{
"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"
原来这是由于组件库中的符号链接反应问题
https://reactjs.org/warnings/invalid-hook-call-warning.html#duplicate-react
通过运行链接中的步骤修复: