0

我正在尝试在自定义 npm 组件中使用反冲,以便我可以在应用程序中发布和使用它,但使用时出现如下错误:

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

> const useStoreRef = () => useContext(AppContext);

我正在使用以下rollupjs来构建包:

rollup.config.js

import babel from "@rollup/plugin-babel";
import commonjs from "@rollup/plugin-commonjs";
import resolve from "@rollup/plugin-node-resolve";
import external from "rollup-plugin-peer-deps-external";
import postcss from "rollup-plugin-postcss";
import postcssImport from "postcss-import";
import packageJSON from "./package.json";

const input = "./src/index.js";

const PLUGINS = [
  babel({
    exclude: "node_modules/**",
  }),
  external(),
  resolve({
    jsnext: true,
    main: true,
    browser: true,
  }),
  commonjs(),
  postcss({
    plugins: [postcssImport()],
  }),
];

export default [
  // CommonJS
  {
    input,
    output: {
      file: packageJSON.main,
      format: "cjs",
      sourcemap: true,
    },
    plugins: PLUGINS,
  },
];

.babelrc

{
    "presets": ["@babel/preset-env", "@babel/preset-react"],
    "plugins": ["@babel/plugin-proposal-class-properties"]
}

src/index.js

import React, { useEffect, useState, useCallback } from "react";
import { useRecoilState, useSetRecoilState } from "recoil";
import {atomState} from '../recoil/atom';

const Component = () => {
    const [state, setState] = useRecoilState(atomState);

    ...
    ...

    return <div>
        ...
        {state}
        ...
    </div>
}

在应用程序中,发布的组件使用如下:

应用程序.js

import {Component} from "NPM_PACKAGE_NAME";
import {RecoilRoot} from "recoil";

<RecoilRoot>
    <Component />
</RecoilRoot>

请帮助解决这个问题。我是新来的js。提前致谢。

注意:我正在yarn link使用该包

4

1 回答 1

1

我在这方面看到了一些 GitHub 问题。显然,仅当您yarn link在应用程序中使用包时才存在此问题。如果我要发布到 npm 注册表并使用它,它会按预期工作。

于 2020-08-31T05:35:05.910 回答