reactjs - 无法在汇总中的 commonJS 插件中获取 ReactDOM 的 namedExports
问题描述
我正在尝试使用 CommonJS 插件在 Rollup.js 中包含 React 和 ReactDOM namedExports。
对我来说 React 对象是正确的,但 ReactDOM 是未定义的。
想知道需要什么改变以及如何 React 对象不为空
使用下面的代码在 rollup.config.js 中,我将 React 作为对象,但 ReactDOM 是空的。
namedExports: {
'node_modules/react/react.js':
['Children', 'Component', 'PropTypes', 'createElement'],
'node_modules/react-dom/index.js': ['render']
}
还应该定义 ReactDOM 对象以及它是如何为 React 工作的。
即使我没有告诉使用 React
解决方案
更新只是偶然发现了 TrySound在此评论中显示的这个更简洁且几乎“自动”的解决方案。我刚刚试了一下,它按预期工作。另外我想说,在React 支持 esm 之前,这似乎是首选方式。
import commonjs from '@rollup/plugin-commonjs';
import * as react from 'react';
import * as reactDom from 'react-dom';
import * as reactIs from 'react-is';
import * as propTypes from 'prop-types';
export default {
...
plugins: [
...
commonjs({
namedExports: {
react: Object.keys(react),
'react-dom': Object.keys(reactDom),
'react-is': Object.keys(reactIs),
'prop-types': Object.keys(propTypes),
},
}),
]
}
原始答案
希望你现在明白了。为了将来对他人和我自己的参考,这对我有用:
// note `rollup-plugin-commonjs` has been deprecated in favor of `@rollup/plugin-commonjs`
import commonjs from '@rollup/plugin-commonjs';
export default {
// [..] other configs like `input` & `output`
plugins: [
commonjs({
include: 'node_modules/**',
// left-hand side can be an absolute path, a path
// relative to the current directory, or the name
// of a module in node_modules
namedExports: {
'node_modules/react/index.js': [
'cloneElement',
'Component',
'createContext',
'createElement',
'createRef',
'forwardRef',
'Fragment',
'isValidElement',
'lazy',
'memo',
'Profiler',
'PureComponent',
'StrictMode',
'Suspense',
'useCallback',
'useContext',
'useDebugValue',
'useEffect',
'useImperativeHandle',
'useLayoutEffect',
'useMemo',
'useReducer',
'useRef',
'useState',
'version',
],
'node_modules/react-dom/index.js': [
'findDOMNode',
'render',
'unmountComponentAtNode',
],
'node_modules/react-dom/server.js': [
'renderToStaticMarkup',
'renderToString',
],
'node_modules/react-is/index.js': [
'AsyncMode',
'ConcurrentMode',
'ContextConsumer',
'ContextProvider',
'Element',
'ForwardRef',
'Fragment',
'isAsyncMode',
'isConcurrentMode',
'isContextConsumer',
'isContextProvider',
'isElement',
'isForwardRef',
'isFragment',
'isLazy',
'isMemo',
'isPortal',
'isProfiler',
'isStrictMode',
'isSuspense',
'isValidElementType',
'Lazy',
'Memo',
'Portal',
'Profiler',
'StrictMode',
'Suspense',
'typeOf',
],
},
}),
],
}
不完全确定这是列出(几乎)所有出口的最佳方法和/或必要/好的方法,但它有效。
如果这是正确的用法,它可以打包也许我会这样做,一旦我弄清楚这是否是要走的路。
相关链接:
- @rollup/plugin-commonjs README
- Rich Harris(Rollup 的创建者)的评论
推荐阅读
- c# - Unity C#改进通用get组件方法
- excel - VBA使用多个数据系列创建xy散点图
- html - 使用CSS中的多个背景仅将灰度应用于一个背景图像?
- jquery - 通过jQuery的AJAX调用特定按钮后不起作用
- c++ - 为 GCC 复制 clang 的 __builtin_assume
- .net - 如何在 Outlook 日历中显示重复事件系列中一个或多个事件的编辑?
- c# - C# WPF 绘图网格
- django - django.db.utils.OperationalError:无法连接到服务器:连接被拒绝
- angular - 角度拖放交点(例如表格中的行和列)
- python - 如何使用openpyxl将一个excel文件的列值与Python中另一个excel文件的列值进行比较?