Closed songquanpeng closed 1 year ago
That could be an option @fwouts. I think we should still try to get v22 to work, but we could go there if we can't get it for v3.
How is https://github.com/vitejs/vite/pull/7894 labeled 'nice-to-have'. Vite is straight up broken for react users that are unlucky to use an affected dependency. The worst about it is that you only realize it when you try to deploy production.
For anyone desperately needing a fix.
Setup patch-package
Create ./patches/vite+2.9.9.patch
diff --git a/node_modules/vite/dist/node/chunks/dep-59dc6e00.js b/node_modules/vite/dist/node/chunks/dep-59dc6e00.js
index 3548bb3..8c5a766 100644
--- a/node_modules/vite/dist/node/chunks/dep-59dc6e00.js
+++ b/node_modules/vite/dist/node/chunks/dep-59dc6e00.js
@@ -14471,6 +14471,38 @@ const exportsPattern = /^(?:module\.)?exports(?:\.([a-zA-Z_$][a-zA-Z_$0-9]*))?$/
const functionType = /^(?:FunctionDeclaration|FunctionExpression|ArrowFunctionExpression)$/;
+
+/**
+ * Determines if a node is an expression containing a `require` call
+ * @param {ASTNode} node - ast node to check
+ * @returns {boolean}
+ */
+ function isRequireExpression(node) {
+ if (!node) return false;
+ // check node type
+ switch (node.type) {
+ case 'CallExpression':
+ case 'NewExpression':
+ // check for `require('x')` or `new require('x')`
+ if (node.callee.type === 'Identifier') {
+ return node.callee.name === 'require';
+ }
+ // check for `require('x')('y')`, `new require('x')('y')`, or `new (require('x'))`
+ if (node.callee.type === 'CallExpression' || node.callee.type === 'NewExpression') {
+ return isRequireExpression(node.callee);
+ }
+ return false;
+ case 'MemberExpression':
+ // check for `require('x').y`
+ return isRequireExpression(node.object);
+ case 'AssignmentExpression':
+ return isRequireExpression(node.right);
+ default:
+ return false;
+ }
+}
+
+
function transformCommonjs(
parse,
code,
@@ -14504,6 +14536,8 @@ function transformCommonjs(
let programDepth = 0;
let currentTryBlockEnd = null;
let shouldWrap = false;
+ let reexports = false;
+
const globals = new Set();
@@ -14586,8 +14620,9 @@ function transformCommonjs(
if (hasDefineEsmProperty(node.right)) {
shouldWrap = true;
}
- } else if (defaultIsModuleExports === false) {
+ } else if (isRequireExpression(node.right, scope)) {
shouldWrap = true;
+ reexports = true;
}
}
} else if (exportName === KEY_COMPILED_ESM) {
@@ -14879,7 +14914,9 @@ function transformCommonjs(
(shouldWrap || (uses.exports && moduleExportsAssignments.length > 0));
const detectWrappedDefault =
shouldWrap &&
- (topLevelDefineCompiledEsmExpressions.length > 0 || code.indexOf('__esModule') >= 0);
+ (reexports ||
+ topLevelDefineCompiledEsmExpressions.length > 0 ||
+ code.indexOf('__esModule') >= 0);
if (
!(
If you're patching a different vite version you probably have to replace dep-59dc6e00.js
with the new chunk filename
🚀 ✌️
Hi @juspky. Another PR has been merged that allows Vite to stop using @rollup/plugin-commonjs
in production builds (see #8280). You should test Vite's latest alpha version and report back if it fixes this issue. Note that you'll need to use the alpha version of @vitejs/plugin-react
as well.
If you're patching a different vite version you probably have to replace
dep-59dc6e00.js
with the new chunk filename
Your patch probably won't work with any other version, since you'd likely need to update the line numbers.
Hi @aleclarson
Awesome, the current alpha fixed the issue for me.
However a new issue has occurred in the alpha. one of my useRef.current is null in production builds https://imgur.com/a/qeELLa2 I've double checked it works flawless in develop mode.
Feel free to get in touch if you need additional information
@juspky thanks for testing the alpha, and good to know the issue is resolved there. Please create a new bug report with a minimal reproduction of the problem you experience with it.
I can't really replicate it because I don't know where the issue is coming from.
Its really weird. sometimes all components work perfectly fine. Then I rebuild and it doesnt work. I've tried a few things but so far I only got it to happen occasionally.
I'll create an issue when I figure out more, atleast the commonjs issue is solved soon 🎉
I'm completely lost as to how Vite works internally so I am unable to help, but I will add that the library that was giving me issues is https://www.npmjs.com/package/react-phone-input-2, and the fix for now is the one suggested by @haikyuu:
import RPI from "react-phone-input-2"; // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore const ReactPhoneInput = RPI.default ? RPI.default : RPI;
After migrating from Create React App to Vite that same library react-phone-input-2
started giving me issues and your solution worked perfectly, thank you very much for sharing it @Kylar13!
I'm completely lost as to how Vite works internally so I am unable to help, but I will add that the library that was giving me issues is https://www.npmjs.com/package/react-phone-input-2, and the fix for now is the one suggested by @haikyuu:
import RPI from "react-phone-input-2"; // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore const ReactPhoneInput = RPI.default ? RPI.default : RPI;
After migrating from Create React App to Vite that same library
react-phone-input-2
started giving me issues and your solution worked perfectly, thank you very much for sharing it @Kylar13!
Same here. Thanks @Kylar13 !
Shorter version here:
import RPI from "react-phone-input-2";
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
const ReactPhoneInput = RPI.default ?? RPI;
For anyone still having this problem, bump vite to v3 (merged #8743) did the trick for me.
Still seeing these in v3, stack traces on these errors are completely unreadable and sourcemap
option is not able to resolve those stack traces either.
FTR, module that errored was this one.
my culprit was react-cookie-consent
, i had to bump vite
to v3, and also react-cookie-consent
to the latest version, then it worked. vite@3 alone didnt solve the issue
if you need to run a development build, to see the stacktrace, run vite build --mode development
(i had to search for this for some time)
Hacky solution in my case
In my case it was coming from using
react-switch
. And I hacked it to work using the following (don't tell anyone about this)import S from "react-switch"; const Switch = S.default? S.default: S console.log(S); // inspecting
I had this same issue with the react-dropzone-uploader package and this helped fix it. Thanks so much
Thank you all! This was a life saver in my case (react-select + TypeScript):
import RS from 'react-select';
const ReactSelect = (RS as any).default ? (RS as any).default : RS;
export const MyComponent = () => {
return (
<ReactSelect options={[]} />
);
};
My React app was crashing in production only with:
Uncaught Invariant Violation: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object
No development nor build issues of any kind. It took me hours to find the cause.
I'm completely lost as to how Vite works internally so I am unable to help, but I will add that the library that was giving me issues is https://www.npmjs.com/package/react-phone-input-2, and the fix for now is the one suggested by @haikyuu:
import RPI from "react-phone-input-2"; // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore const ReactPhoneInput = RPI.default ? RPI.default : RPI;
you saved my life. thanks a lot
For me it was react-datetime Thanks for the solution!
import DT from "react-datetime";
// @ts-ignore
const DateTime = DT.default ? DT.default : DT;
For me it was @mdi/react
Just want to add my 5 cents on this issue...
I've spent ~20hours migrating large project from CRA2 to vite. 100s of changed files, writing custom plugins and it finally worked on dev and prod.
Imagine my frustration, when I see some of the pages crush because rollup can't handle cjs files in the same way as esbuild or webpack does. Imagine my frustration, when I see such hyped project as vite having this issue opened for 2 years.
Since rollup struggles to fix this issue, vite should implement its own rollup plugin to reexport cjs in the same way as esbuild does.
I also encountered this issue in the library react-foco
,
My temporary solution is to force cjs tranform to use default field.
export default defineConfig({
build: {
...
commonjsOptions: {
defaultIsModuleExports(id) {
if (/react-foco/.test(id)) return false; // cannot automatically detect react-foco's default export, fix a rollup issue https://github.com/vitejs/vite/issues/2139
return 'auto';
},
},
},
I found downgrade @rollup/plugin-commonjs
to version 21 also fix the issue for me. To use custom version of @rollup/plugin-commonjs
, we can do this
import commonjs from '@rollup/plugin-commonjs'; // our version of commonjs plugin
defineConfig({
build: { commonjsOptions: { include: [] } },
plugins: [commonjs()]
})
I had the same issue and now the error is fixed. I added a few lines of code in Vite config.
I'm using @vitejs/plugin-react: 2.2.0
and vite: 3.2.3
@mdi/react
same, changing default to named import was the fix for me
I have the same issue but only sometimes 😸. Vite (or more likely rollup?) doesn't produce deterministic outputs in our case. The lucky output snippet is:
var _Checkbox$1 = _interopRequireDefault$8(requireCheckbox());
var _default$a = Checkbox$2.default = _Checkbox$1.default;
...
react.exports.createElement(_default$a) // ok
while sometimes it produces
function requireCheckbox() {
...
Checkbox$2.__esModule = true;
var _Checkbox2 = _interopRequireDefault2(requireCheckbox$1());
Checkbox$2.default = _Checkbox2.default;
return Checkbox$2;
}
var CheckboxExports = requireCheckbox();
...
react.exports.createElement(CheckboxExports) // crashes because {__esModule: true, default: f} is obviously no valid react type
Same issue with 4.0.0-alpha.6. I was able to workaround it with the hacky solution https://github.com/vitejs/vite/issues/2139#issuecomment-824557740. But non deterministic results really scare me to use vite in production.
Getting the same issue
Still same issue (with react-audio-player
).. what is the recommended fix or workaround as of now?
Hit this with @mdi/react as well, for typescript I added to the fix proposed in https://github.com/vitejs/vite/issues/2139#issuecomment-802981228 to preserve types
Icon.tsx
import I from '@mdi/react';
// @ts-ignore
const IconComponent = I.default ? I.default : I;
const Icon: typeof I = IconComponent;
export default Icon;
Hit this with @mdi/react as well, for typescript I added to the fix proposed in #2139 (comment) to preserve types
Icon.tsx
import I from '@mdi/react'; // @ts-ignore const IconComponent = I.default ? I.default : I; const Icon: typeof I = IconComponent; export default Icon;
You can also use
import { Icon } from '@mdi/react';
instead of the default import, that fixed it for me.
I had the same problem of @songquanpeng, The solution in my case was update vite version 2 to 4
It seems this is still not fixed with Vite 4.0.4
I made a sample project with Vite 4.0.4 and template react-ts
. Created an <ErrorBoundary />
around <App />
in main.tsx
and once I added in react-phone-input-2
using the default import (or any other package that causes the issue), the "Minified React error #130" was shown in the error boundary in a production build.
Build process:
pnpm run build
pnpx http-server dist --port 3002
If I use the workaround
import RPI from 'react-phone-input-2'
// @ts-ignore
const PhoneInput = RPI.default ? RPI.default : RPI
then the error goes away in production.
Still getting this issue in Vite 4.0.4.
This is an awful error because: a) you don't see it in dev (deploying is the only way to try and fix it?) b) there's no way apart from trial-and-error to find out the culprit c) this has seemingly been open since 2021 without any meaningful progress
I'd love to be wrong on any of these points
I also encountered this problem while dealing with vite and react-phone-input-2
package.
After a couple of hours trying to understand @rollup/plugin-commonjs
and how defaultIsModuleExports
flag affects modules, I came up with a (possibly not the silver bullet but working) solution.
Plugin (at this moment of writing) handles package bundles with default exports only when module.exports=...
it's either an object expression (with truthy __esModule
property value) or a require
call function. This (and probably other technics added to the plugin over time) solve problems with some of the mentioned above dependencies (react-switch
, react-cookie-consent
, react-foco
, react-select
) but others (like react-audio-player
, react-date-time
, @mdi/react
and react-phone-input-2
) are basically IIFE's putted into module.exports, which are not covered by the plugin.
Playing with AST parsers and walkers doesn't give me much progress (at some point it's just too hard to handle with all those nodes), but having in mind, that defaultIsModuleExports
flag accepts a function with an argument of package path, I ended up with this:
import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
// Without it dynamic require is not possible in config file
import { createRequire } from "module";
const require = createRequire(import.meta.url);
export default defineConfig({
build: {
commonjsOptions: {
defaultIsModuleExports(id) {
const module = require(id);
if (module?.default) {
return false;
}
return "auto";
},
},
},
plugins: [react()],
});
All IIFE packages are now converted by plugin to have same export structure both in localhost and production. Probably in larger projects, it could potentially slow down the build process, but IMO it's better than manually putting a ternary operator on each file.
Is there any linting rule we can use to prevent this bug from happening in prod?
Slightly modified solution by @Boni0 This config works for my case:
import { defineConfig} from 'vite';
import react from '@vitejs/plugin-react';
import { viteCommonjs } from '@originjs/vite-plugin-commonjs';
export default defineConfig({
plugins: [viteCommonjs(), react()],
build: {
commonjsOptions: {
defaultIsModuleExports(id) {
try {
const module = require(id);
if (module?.default) {
return false;
}
return 'auto';
} catch (error) {
return 'auto';
}
},
transformMixedEsModules: true,
},
},
});
Tried several suggestions to try and debug, but even this is a bug:
mode: "development",
build: {
minify: false,
},
Which gets ignored and continues to minify during build even though while building it states "vite v4.1.1 building for development...", and yet still get:
Unexpected Application Error!
Minified React error #130; visit https://re...
during preview, and deployment i.e. Vercel.
Still getting Minified React error #130 after trying suggestions above, and its funny. In the link presented I'm informed "We highly recommend using the development build...", lol, I'm trying to!!!!
Replying for google hits in case anyone elses searches for the library:
This tripped me up with react-modal
. I fixed it, as above,
import * as RM from 'react-modal/lib';
const ReactModal = (RM as any).default || RM;
Glad I came across this thread. Kinda appreciate create-react-app.
stick to create-react-app, this is bs. Stuck with this error in production with no clue what is causing it
stick to create-react-app, this is bs. Stuck with this error in production with no clue what is causing it
It's an issue with one of your imports. The way it's importing with export default is conflicting with how vite is processing modules
// this import causes an issue and I can't import it as { StyledFirebaseAuth }
import StyledFirebaseAuth from "react-firebaseui/StyledFirebaseAuth";
export const AuthComponent = (StyledFirebaseAuth as any).default
? (StyledFirebaseAuth as any).default
: StyledFirebaseAuth;
I'm migrating a CRA app to Vite, and I encountered an error in dev mode:
react-dom.development.js:26923 Uncaught TypeError: _events2.default is not a constructor
at BootstrapTableContainer.RemoteResolver (remote-resolver.js:132:29)
at new BootstrapTableContainer (index.js:72:138)
at constructClassInstance (react-dom.development.js:14323:18)
at updateClassComponent (react-dom.development.js:19688:5)
at beginWork (react-dom.development.js:21611:16)
at beginWork$1 (react-dom.development.js:27426:14)
at performUnitOfWork (react-dom.development.js:26557:12)
at workLoopSync (react-dom.development.js:26466:5)
at renderRootSync (react-dom.development.js:26434:7)
at recoverFromConcurrentError (react-dom.development.js:25850:20)
FYI, I did not update these dependencies, I simply migrated the from react-scripts to Vite. In my search, I came across the following:
But none of the solutions/workarounds presented anywhere actually worked, I was able to make only the dev mode work by using a suggested solution -- which to use polyfills, but then when I build for production, I get this error right here here.
The app was working and building properly without these errors when using react-scripts, and I'm kinda stuck at the moment and don't know where to go from here.
@aprilmintacpineda the error you show doesn't seems related to this issue or the other links you listed. If you find an issue with Vite, and you would like to help the project, please create a minimal reproduction of your problem and a new bug report. But if you are happier with CRA, you should probably avoid migrating your project.
@patak-dev Okay maybe the following line wasn't clear.
I was able to make the dev mode work by using the suggested solution -- which to use polyfills and stuff, but then I get this error here. Which again, doesn't happen in CRA.
I edited it to be clearer.
My comment is actually complete together with the trace of where it started until where it is now, if you just read with the intent to understand -- the error started on bootstrap (and I added relevant links) which I was able to fix on dev mode, then after fixing that on dev mode and built for production, I got this error here which is already 3 years old.
@aprilmintacpineda thanks for the edit, that makes your comment more clear. Your comment doesn't add anything to this issue in particular though, so I suggest avoiding this kind of interaction with OSS projects. For example, you can provide a better minimal reproduction, or dig into this issue and try to see if you see other solutions that we haven't yet seen for it.
@aprilmintacpineda thanks for the edit, that makes your comment more clear. Your comment doesn't add anything to this issue in particular though, so I suggest avoiding this kind of interaction with OSS projects. For example, you can provide a better minimal reproduction, or dig into this issue and try to see if you see other solutions that we haven't yet seen for it.
I think my comment is complete with the leads, I posted that comment in hopes that someone will look into those leads and find a solution or an explanation on why this is happening on various projects. In addition to that, I'm not the only one experiencing the error, so I think it's good that everyone is putting in leads that may contribute to the problem being solved.
If you didn't find my comment useful, you always have the choice to ignore it just as you ignored all other comments above. This begs the question, why didn't you? Why did you find the need to respond to my comment but completely ignore the rest above? must be because I pointed out something obvious, which is that this issue has been ignore for 3 years and that it doesn't happen in CRA, and that offended you and provoked you to post comments that attempt to gatekeep me. I apologize for that, I may have phrase my comment in an offensive manner. I have edited my comment, hopefully this edited version is not as offensive to you (and to others too).
Anyway, I just wanted to clarify my intent on the comment, it seems like you're taking me for an idiot who randomly posts comments on random issues on random github repositories -- I assure you, I am not. My comment was actually clear even without the edit, you simply read with the intent to judge rather than understand. I recommend not practicing this gatekeeping behavior on OSS projects, OSS is "open" not "closed" you should expect all sorts of comments to come through and you should exercise your ability to ignore (just as you've previously done) rather than react. Thank you for your time.
Again, what I said was that your comment was not helpful for this issue in particular. Thanks for editing the original post that ended with "Funny thing is, this issue is now 3 years old! Can you imagine that?". I took the time to answer you and avoid ignoring your post or marking it as spam because of that last line. Please let's move now this discussion to a better forum, I invite you to join https://chat.vitejs.com where we can chat about what accounts to healthy OSS interactions without notifying everyone that is subscribed to this issue (because they are interested in the issue itself and not in our discussion here). Thanks!
https://github.com/vitejs/vite/issues/2139#issuecomment-1399098579 This is the actual solution for the problem which works pretty well. Recently I have migrated one of my big projects from CRA to Vite. Then after the build, I was getting that issue on my product. This solution helped me. Thanks a lot.
There is some package that causes this error. Please remove those packages to solve this error. In my case, I installed an animation package and it caused this error. Then I wasn't sure but I removed this package and solved the error.
As I have said I just migrated one of my big projects from CRA to Vite and you know there are a lot of dependencies. So, it is not even possible to detect the actual culprit. So, I was looking for a solution and the above comment was very helpful to me.
Hi there, I have the same problem. It's telling me I have an invalid hook call and I have gone file by file looking for the repeated React import or hook used outside of a React component and found nothing substantial. Tried several changes including all of the above and still see the same error. In my case this is the libraries used:
"axios": "^1.2.1",
"file-saver": "^2.0.5",
"js-cookie": "^3.0.1",
"react": "^18.2.0",
"react-animate-height": "^3.1.1",
"react-countup": "^6.4.0",
"react-dom": "^18.2.0",
"react-loading": "^2.0.3",
"react-router-dom": "^6.6.0",
"react-select": "^5.7.0",
"react-toastify": "^9.1.1",
"recharts": "^2.2.0"
I'm pretty sure I can remove any of these packages for another one, do you think it's coming form one of them?
This is my exact error btw:
at it (blur.js:42:3933)
at s.useContext (blur.js:42:5675)
at cr (blur.js:57:31858)
at blur.js:61:494
at blur.js:126:5191
at Generator.next (<anonymous>)
at I (blur.js:126:4967)
What can I do? I am afraid of breaking production.
Can you copy your full error? And when you are getting this error? On vite build or where?
Hey there, didn't realise the error got cut somehow. Here is it in full:
Uncaught (in promise) Error: Minified React error #321; visit https://reactjs.org/docs/error-decoder.html?invariant=321 for the full message or use the non-minified dev environment for full errors and additional helpful warnings.
at it (blur.js:42:3933)
at s.useContext (blur.js:42:5675)
at cr (blur.js:57:31858)
at blur.js:61:494
at blur.js:126:5191
at Generator.next (<anonymous>)
at I (blur.js:126:4967)
It says it's coming from context, here is my context ( simplified ) :
import axios from "axios";
import React, { useState, createContext, useEffect } from "react";
import Cookies from "js-cookie";
import Loading from "../components/general/Loading";
import { api } from "../helpers/api";
export const AuthContext = createContext(null);
export const AuthProvider = ({ children }) => {
const [user, setUser] = useState(null);
const [isLoggedIn, setIsLoggedIn] = useState(null);
const getUserInfo = async () => { ... };
const updateUserInfo = async () => { ... };
useEffect(() => {
const checkAuthCookie = async () => { ... };
checkAuthCookie();
}, []);
const login = (receivedUser) => { ... };
const logout = () => { ... };
if (isLoggedIn === null) return <Loading />;
return (
<AuthContext.Provider
value={{ user, isLoggedIn, login, logout, updateUserInfo }}
>
{children}
</AuthContext.Provider>
);
};
`` Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
This is basically the error that is happening on your code said by the error code decoder of React. Take a look over your code, so you can confirm that your code doesn't contain any of mentioned above issues.
Describe the bug
Encountered “Minified React error” in the production environment, the dev environment is fine.
Reproduction
Repo: https://github.com/songquanpeng/snippet-manager/tree/aa02a582c676bd3dcd5254f18d7087bb8a1a7220
My React application is on the
web
folder.System Info
vite
version: 2.0.0Summarization of the root problem
https://github.com/vitejs/vite/issues/2139#issuecomment-1024852072