Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

When there is a conditional dynamic require in the code, the module reference will be hoisted to the top level, resulting in an error when actually using it #831

Unanswered
NexxLuo asked this question in Q&A
Discussion options

  1. 以下是一段react 18 、react17的一段兼容性代码,根据判断版本调用不同的api

image

  1. 最终生成的文件内容将包引用一同提升到了顶层,会导致此判断出错

image

3.当引用此包的宿主环境安装的react版本为17时,编译报错如下
image

You must be logged in to vote

Replies: 2 comments 3 replies

Comment options

I think even if you keep your source code in the application side, it will still report an error.

 try {
 const { createRoot } = require("react-dom/client");
 } catch (err) {
 const readDOM = require("react-dom");
 }

IMO, this should not be a runtime decision.

You must be logged in to vote
1 reply
Comment options

For example, this is how Storybook handle multiple React versions via build tool configuration https://github.com/storybookjs/storybook/blob/next/code/lib/react-dom-shim/src/preset.ts.

Comment options

我已经通过在require中使用变量来规避这个问题,如下:
image

rslib这个行为和webpack以及其他相关工具(如@umijs/father)的行为是不一致的;希望后续会有比较好的处理方式

You must be logged in to vote
2 replies
Comment options

Yes, it will be an issue in some scenario. We will try to fix that in the future.

Comment options

和webpack以及其他相关工具(如@umijs/father)的行为是不一致的

This should be inconsistent with esbuild, but hoisting behaviour should be same in webpack/Rspack/Rslib. Can you show some configs of your project?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet

AltStyle によって変換されたページ (->オリジナル) /