使用 rollup.js 创建 React 库时出现错误 null(读取“useState”)

问题描述 投票:0回答:2

我正在使用 rollup.js 创建一个 React 库,但是当我运行

npm run build
时出现错误 就好像尝试从
useState
 检索 
null

钩子一样
Uncaught TypeError: Cannot read properties of null (reading 'useState')
    at Object.useState (react.development.js:1617:1)
    at ReactPokableLoving (index.esm.js:20:1)
    at renderWithHooks (react-dom.development.js:14985:1)
    at mountIndeterminateComponent (react-dom.development.js:17811:1)
    at beginWork (react-dom.development.js:19049:1)
    at HTMLUnknownElement.callCallback (react-dom.development.js:3945:1)
    at Object.invokeGuardedCallbackDev (react-dom.development.js:3994:1)
    at invokeGuardedCallback (react-dom.development.js:4056:1)
    at beginWork$1 (react-dom.development.js:23964:1)
    at performUnitOfWork (react-dom.development.js:22776:1)

这里是我的 rollup.config.js

import { babel } from "@rollup/plugin-babel";

const config = {
  input: "src/lib/index.js",
  output: {
    file: "dist/index.esm.js",
    format: "esm",
  },
  external: [/@babel\/runtime/, "react", "react-dom"],
  plugins: [
    babel({
      babelHelpers: "runtime",
      plugins: ["@babel/plugin-transform-runtime"],
    }),
  ],
};

export default config;

我的.babelrc

{
    "presets" : [["@babel/preset-env", {"targets" : "defaults"}],[
            "@babel/preset-react",
            {
                "runtime": "automatic"
            }
        ]]
}

和我的package.json

{
  "name": "xxxxx",
  "version": "1.0.7",
  "author": "ndotie",
  "keywords": [
    "react",
    "components",
    "ui",
    "pagination"
  ],
  "module": "dist/index.esm.js",
  "repository": {
    "type": "git",
    "url": "https://github.com/xxx/xxxx.git"
  },
  "files": [
    "dist",
    "README.md"
  ],
  "private": false,
  "dependencies": {
    "@babel/polyfill": "^7.12.1",
    "@babel/runtime": "^7.17.9",
    "@testing-library/jest-dom": "^5.16.4",
    "@testing-library/react": "^12.1.4",
    "@testing-library/user-event": "^13.5.0",
    "react": "^18.0.0",
    "react-dom": "^18.0.0", 
    "react-scripts": "5.0.0",
    "rollup": "^2.70.1",
    "web-vitals": "^2.1.4"
  },
  "scripts": {
    "start": "react-scripts start",
    "test": "react-scripts test",
    "eject": "react-scripts eject",
    "prebuild": "rimraf dist",
    "build": "rollup -c"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  },
  "devDependencies": {
    "@babel/cli": "^7.17.6",
    "@babel/core": "^7.17.9",
    "@babel/plugin-transform-runtime": "^7.17.0",
    "@babel/preset-env": "^7.16.11",
    "@babel/preset-react": "^7.16.7",
    "@rollup/plugin-babel": "^5.3.1",
    "cross-env": "^7.0.3"
  }
}
reactjs rollupjs
2个回答
8
投票

我面临同样的问题并成功解决该问题,您在

rollup.config
文件中缺少一些配置:

external: ["react", "react-dom"]

我将附上完整的配置来创建一个包含 rollup、react(18) 和 typescript 的 npm 包。

rollup.config.js
文件:

//This plugin prevents packages listed in peerDependencies from being bundled with our component library
import peerDepsExternal from "rollup-plugin-peer-deps-external";

//efficiently bundles third party dependencies we've installed and use in node_modules
import resolve from "@rollup/plugin-node-resolve";

// //enables transpilation into CommonJS (CJS) format
import commonjs from "@rollup/plugin-commonjs";

//transpiled our TypeScript code into JavaScript. This plugin will use all the settings we have set in tsconfig.json.
//We set "useTsconfigDeclarationDir": true so that it outputs the .d.ts files in the directory specified by in tsconfig.json
import typescript from "rollup-plugin-typescript2";

// transforms our Sass into CSS. In order to get this plugin working with Sass, we've installed sass
import postcss from "rollup-plugin-postcss";

const packageJson = require("./package.json");

export default {
  input: "src/index.tsx",
  output: [
    {
      file: packageJson.module,
      format: "esm", // import '' from  '...
      sourcemap: true,
    },
  ],
  plugins: [
    peerDepsExternal(),
    resolve(),
    commonjs(),
    typescript({ useTsconfigDeclarationDir: true }),
    postcss(),
  ],
  external: ["react", "react-dom"],
};

ts.config
文件:

{
  "compilerOptions": {
    "target": "es5",
    "outDir": "build",
    "lib": ["dom", "dom.iterable", "esnext"],
    "declaration": true,
    "declarationDir": "build",
    "allowJs": true,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": false,
    "noEmit": true,
    "jsx": "react-jsx",
    "baseUrl": "./src"
  },
  "include": ["src"],
  "exclude": ["node_modules", "build"]
}

package.json
文件:

{
  "name": "test",
  "version": "1.0.0",
  "main": "build/index.js",
  "module": "build/index.js",
  "scripts": {
    "build": "rollup -c",
    "build-watch": "rollup -c -w"
  },
  "license": "MIT",
  "devDependencies": {
    "@rollup/plugin-commonjs": "^22.0.0",
    "@rollup/plugin-node-resolve": "^13.3.0",
    "@types/react": "^18.0.12",
    "@types/react-dom": "^18.0.5",
    "rollup": "^2.75.6",
    "rollup-plugin-peer-deps-external": "^2.2.4",
    "rollup-plugin-postcss": "^4.0.2",
    "rollup-plugin-terser": "^7.0.2",
    "rollup-plugin-typescript2": "^0.31.2",
    "sass": "^1.52.1",
    "typescript": "^4.6.4",
    "react": "^18.1.0",
    "react-dom": "^18.1.0",
  }
}

注意:如果您在 React 应用程序中使用

npm link
来测试库,则应从包中删除
react
react-dom
依赖项,而不应将库链接到
react
react-dom 
在您的应用程序中发现,这样做是为了避免在测试库时出现 React 的双重副本(了解更多信息此处


0
投票

我遇到了同样的问题,这对我有用

1) 在 package.json 中

"peerDependencies": { "react": "^18.2.0" },

2) 在 rollup.config.js 中添加 rollup-plugin-peer-deps-external

使用

npm i rollup-plugin-peer-deps-external

下载插件

将插件导入您的

rollup.config.js

import peerDepsExternal from "rollup-plugin-peer-deps-external";

在您的插件中运行它`

plugins: [
      peerDepsExternal(),
      resolve(),
      commonjs(),
      typescript({ tsconfig: "./tsconfig.json" }),
      postcss(),
    ],

`

这是 rollup.config.js 对我来说的样子

import resolve from "@rollup/plugin-node-resolve";
import commonjs from "@rollup/plugin-commonjs";
import typescript from "@rollup/plugin-typescript";
import postcss from "rollup-plugin-postcss";
import dts from "rollup-plugin-dts";
import peerDepsExternal from "rollup-plugin-peer-deps-external";

const packageJson = require("./package.json");

export default [
  {
    input: "src/index.ts",
    external: ["react-dom"],
    output: [
      {
        file: packageJson.main,
        format: "cjs",
        sourcemap: true,
      },
      {
        file: packageJson.module,
        format: "esm",
        sourcemap: true,
      },
    ],
    plugins: [
      peerDepsExternal(),
      resolve(),
      commonjs(),
      typescript({ tsconfig: "./tsconfig.json" }),
      postcss(),
    ],
  },
  {
    input: "dist/esm/types/index.d.ts",
    output: [{ file: "dist/index.d.ts", format: "esm" }],
    plugins: [dts()],
    external: [/\.(css|less|scss)$/, "react", "react-dom"],
  },
];
© www.soinside.com 2019 - 2024. All rights reserved.