'rollup-plugin-node-resolve' 无法使用 react 的 useState,如何解决?

'rollup-plugin-node-resolve' can't work with `useState` of react, how to fix it?

在打字稿项目中,我使用 typescript + rollup + rollup-plugin-node-resolve + React 的 useState 一起使用,但是当 运行 rollup -c ,它抛出错误:

1: import {useState} from "react";
           ^
2: 
Error: 'useState' is not exported by node_modules/react/index.js

我的代码很简单:

import {useState} from "react";

console.log(useState);

rollup.config.js 是:

import commonjs from 'rollup-plugin-commonjs';
import resolve from 'rollup-plugin-node-resolve';
import typescript from 'rollup-plugin-typescript2';

export default {
  input: 'index.ts',
  output: [
    {
      file: 'bundle.js',
      format: 'cjs',
    }
  ],
  plugins: [
    resolve(),
    commonjs(),
    typescript(),
  ]
};

package.json 是:

{
  "scripts": {
    "demo": "rollup -c && node bundle.js"
  },
  "dependencies": {
    "react": "16.8.4"
  },
  "devDependencies": {
    "@types/react": "16.8.8",
    "rollup": "1.6.0",
    "rollup-plugin-commonjs": "9.2.1",
    "rollup-plugin-node-resolve": "4.0.1",
    "rollup-plugin-typescript2": "0.20.1",
    "typescript": "3.3.3333"
  }
}

tsconfig.json:

{
  "compilerOptions": {
    "strict": true,
    "target": "es6",
    "module": "esnext",
    "noImplicitAny": true,
    "removeComments": true,
    "preserveConstEnums": true,
    "moduleResolution": "node",
    "sourceMap": true,
    "jsx": "react",
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true
  }
}

如果我从 rollup.config.js 中删除 resolve(),rollup 将正确地捆绑它。但是我需要在我的真实项目中使用resolve()

哪里错了,如何解决?

PS:完整的代码演示在这里:https://github.com/freewind-demos/typescript-react-rollup-use-state-demo

作为@Tholle 提供的答案link,问题是 rollup-plugin-commonjs 无法从 react 中找到 setState 导出,因为 react 将其声明为:

const React = {
    setState
}
module.exports = React

rollup-plugin-commonjs 无法处理这种形式的导出,因此我们必须在 rollup.config.js 中定义一些命名导出,例如:

plugins: [
   'react': ['useState']
]

这个设置配置适合我

// rollup config 
plugins: [
   commonjs({
      // ... other commonjs config options
      namedExports: {
         // https://github.com/rollup/rollup-plugin-commonjs#custom-named-exports
         'node_modules/react/index.js': ['useState', 'useRef', 'useEffect'],
       },
     }),
],

我发现我需要在 package.json:

中添加 peerDependencies
"peerDependencies": {
    "react": "^17.0.1",
    "react-dom": "^17.0.1"
  }