【问题标题】:Usage of recoil in custom NPM component在自定义 NPM 组件中使用反冲
【发布时间】:2020-08-26 12:30:30
【问题描述】:

我正在尝试在自定义 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>
}

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

App.js

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

<RecoilRoot>
    <Component />
</RecoilRoot>

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

注意:我使用yarn link 来使用包

【问题讨论】:

  • 你是否也在包内使用?还是依赖于外部应用程序的包将 包裹在它周围?
  • 我只在应用程序中使用它。而且我尝试了仅在包中或仅在应用程序中使用。两种方式都会抛出相同的错误。

标签: reactjs npm babeljs rollupjs recoiljs


【解决方案1】:

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

【讨论】:

  • 救命稻草,感谢分享 - 我快疯了!
猜你喜欢
  • 2017-01-24
  • 2019-11-08
  • 1970-01-01
  • 1970-01-01
  • 2020-01-18
  • 1970-01-01
  • 2021-08-09
  • 1970-01-01
  • 2022-10-31
相关资源
最近更新 更多