更新 偶然发现了这个comment by TrySound 中显示的更简洁且几乎“自动”的解决方案。我刚刚试了一下,它按预期工作。另外我想说这似乎是until React supports 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
- Comment by Rich Harris (Creator of Rollup)