ndotie
ndotie

Reputation: 2160

Creating react library with rollup.js i get error null (reading 'useState')

Am using rollup.js to create a react library but when i run npm run build i get an error as if useState hook is tried to be retrieved from 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)

here my 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;

my .babelrc

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

and my 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"
  }
}

Upvotes: 9

Views: 5246

Answers (2)

Martin Babak
Martin Babak

Reputation: 11

I had the same problem and this is what worked for me

1) In package.json

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

2) In rollup.config.js add rollup-plugin-peer-deps-external

Download a plugin with npm i rollup-plugin-peer-deps-external

Import a plugin to your rollup.config.js

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

Run it in your plugins

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

Here is how rollup.config.js looks for me

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"],
  },
];

Upvotes: 1

OriEng
OriEng

Reputation: 1573

I face the same problem and had success to resolve that, you missing some configuration in your rollup.config file:

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

I will attach my full configuration to create an npm package with rollup, react(18) and typescript.

rollup.config.js file:

//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 file:

{
  "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 file:

{
  "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",
  }
}

NOTE: if you are testing the library using npm link with react application you should remove the react and react-dom dependencies from your package and instead of that you should link the library to the react and react-dom that found in your application, this is done to avoid the double copy of react when you test the library (read more here )

Upvotes: 14

Related Questions