Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Popper.js:11 Uncaught TypeError: styled_default is not a function at Popper.js:11:20 #12423

Open
7 tasks done
Nefcanto opened this issue Mar 15, 2023 · 58 comments
Open
7 tasks done
Labels
bug: upstream Bug in a dependency of Vite feat: deps optimizer Esbuild Dependencies Optimization

Comments

@Nefcanto
Copy link

Describe the bug

I have updated some of my dependencies.

I expect to see the address of my code in the error call stack.

All I see is this:

Popper.js:11 Uncaught TypeError: styled_default is not a function
    at Popper.js:11:20
(anonymous) @ Popper.js:11

I have also reported it to the MUI Team

I have also seen that it's been asked here.

My problem is that the error does not give us more information. Is it a Vite bug? Is it a bug related to esbuild? Is it a bug of MUI? I literally do not know.

Reproduction

https://github.com/Nefcanto/MuiPopperBug

Steps to reproduce

  1. git clone https://github.com/Nefcanto/MuiPopperBug
  2. cd MuiPopperBug
  3. npm install
  4. npm run dev
  5. Browse and see the error

System Info

System:
    OS: Linux 5.19 Debian GNU/Linux 11 (bullseye) 11 (bullseye)
    CPU: (4) x64 Intel(R) Core(TM) i5-6500 CPU @ 3.20GHz
    Memory: 9.10 GB / 15.52 GB
    Container: Yes
    Shell: 5.1.4 - /bin/bash
  Binaries:
    Node: 18.15.0 - /usr/local/bin/node
    Yarn: 1.22.19 - /usr/local/bin/yarn
    npm: 9.6.1 - /usr/local/bin/npm
  npmPackages:
    @vitejs/plugin-react: ^3.1.0 => 3.1.0 
    vite: ^4.1.4 => 4.1.4

Used Package Manager

npm

Logs

No response

Validations

@Tanimodori
Copy link

Tanimodori commented Mar 16, 2023

A fresh clone of this reproduction do reproduce this error, but if I remove the node_modules sometimes the problem will be fixed.

I see that the cause of this issue and #8308 is missing module initialization.

I replace src/main.jsx with the following content

import { Popper } from "@mui/material";

console.log(Popper);

The Proper here is mui-material/src/Popper/Popper.tsx

// ...
import { styled, Theme, useThemeProps } from '../styles';
// ...
const PopperRoot = styled(PopperUnstyled, {
  name: 'MuiPopper',
  slot: 'Root',
  overridesResolver: (props, styles) => styles.root,
})({});
// ...

Full transformed code by vite:

import {
  PopperUnstyled_default,
  init_PopperUnstyled
} from "/node_modules/.vite/deps/chunk-73GXGH6W.js?v=b24550c9";
import {
  styled_default,
  useThemeProps
} from "/node_modules/.vite/deps/chunk-QGFUN55Y.js?v=b24550c9";
import {
  init_esm as init_esm2,
  useThemeWithoutDefault_default
} from "/node_modules/.vite/deps/chunk-M6YZV643.js?v=b24550c9";
import {
  _objectWithoutPropertiesLoose,
  init_objectWithoutPropertiesLoose
} from "/node_modules/.vite/deps/chunk-KBFHYFJ6.js?v=b24550c9";
import {
  HTMLElementType,
  init_esm,
  refType_default
} from "/node_modules/.vite/deps/chunk-KQS6UZBQ.js?v=b24550c9";
import {
  require_prop_types
} from "/node_modules/.vite/deps/chunk-EOOR7TYC.js?v=b24550c9";
import {
  require_jsx_runtime
} from "/node_modules/.vite/deps/chunk-TNQUW4IY.js?v=b24550c9";
import {
  _extends,
  init_extends
} from "/node_modules/.vite/deps/chunk-6K2CSZVE.js?v=b24550c9";
import {
  require_react
} from "/node_modules/.vite/deps/chunk-JFTBQ7A7.js?v=b24550c9";
import {
  __toESM
} from "/node_modules/.vite/deps/chunk-AC2VUBZ6.js?v=b24550c9";

// node_modules/@mui/material/Popper/Popper.js
init_extends();
init_objectWithoutPropertiesLoose();
init_PopperUnstyled();
init_esm2();
init_esm();
var import_prop_types = __toESM(require_prop_types());
var React = __toESM(require_react());
var import_jsx_runtime = __toESM(require_jsx_runtime());
var _excluded = ["components", "componentsProps", "slots", "slotProps"];
var PopperRoot = styled_default(PopperUnstyled_default, {
  name: "MuiPopper",
  slot: "Root",
  overridesResolver: (props, styles) => styles.root
})({});
var Popper = React.forwardRef(function Popper2(inProps, ref) {
  var _slots$root;
  const theme = useThemeWithoutDefault_default();
  const props = useThemeProps({
    props: inProps,
    name: "MuiPopper"
  });
  const {
    components,
    componentsProps,
    slots,
    slotProps
  } = props, other = _objectWithoutPropertiesLoose(props, _excluded);
  const RootComponent = (_slots$root = slots == null ? void 0 : slots.root) != null ? _slots$root : components == null ? void 0 : components.Root;
  return (0, import_jsx_runtime.jsx)(PopperRoot, _extends({
    direction: theme == null ? void 0 : theme.direction,
    slots: {
      root: RootComponent
    },
    slotProps: slotProps != null ? slotProps : componentsProps
  }, other, {
    ref
  }));
});
true ? Popper.propTypes = {
  // ----------------------------- Warning --------------------------------
  // | These PropTypes are generated from the TypeScript type definitions |
  // |     To update them edit TypeScript types and run "yarn proptypes"  |
  // ----------------------------------------------------------------------
  /**
   * An HTML element, [virtualElement](https://popper.js.org/docs/v2/virtual-elements/),
   * or a function that returns either.
   * It's used to set the position of the popper.
   * The return value will passed as the reference object of the Popper instance.
   */
  anchorEl: import_prop_types.default.oneOfType([HTMLElementType, import_prop_types.default.object, import_prop_types.default.func]),
  /**
   * Popper render function or node.
   */
  children: import_prop_types.default.oneOfType([import_prop_types.default.node, import_prop_types.default.func]),
  /**
   * @ignore
   */
  component: import_prop_types.default.elementType,
  /**
   * The components used for each slot inside the Popper.
   * Either a string to use a HTML element or a component.
   * @default {}
   */
  components: import_prop_types.default.shape({
    Root: import_prop_types.default.elementType
  }),
  /**
   * The props used for each slot inside the Popper.
   * @default {}
   */
  componentsProps: import_prop_types.default.shape({
    root: import_prop_types.default.oneOfType([import_prop_types.default.func, import_prop_types.default.object])
  }),
  /**
   * An HTML element or function that returns one.
   * The `container` will have the portal children appended to it.
   *
   * By default, it uses the body of the top-level document object,
   * so it's simply `document.body` most of the time.
   */
  container: import_prop_types.default.oneOfType([HTMLElementType, import_prop_types.default.func]),
  /**
   * The `children` will be under the DOM hierarchy of the parent component.
   * @default false
   */
  disablePortal: import_prop_types.default.bool,
  /**
   * Always keep the children in the DOM.
   * This prop can be useful in SEO situation or
   * when you want to maximize the responsiveness of the Popper.
   * @default false
   */
  keepMounted: import_prop_types.default.bool,
  /**
   * Popper.js is based on a "plugin-like" architecture,
   * most of its features are fully encapsulated "modifiers".
   *
   * A modifier is a function that is called each time Popper.js needs to
   * compute the position of the popper.
   * For this reason, modifiers should be very performant to avoid bottlenecks.
   * To learn how to create a modifier, [read the modifiers documentation](https://popper.js.org/docs/v2/modifiers/).
   */
  modifiers: import_prop_types.default.arrayOf(import_prop_types.default.shape({
    data: import_prop_types.default.object,
    effect: import_prop_types.default.func,
    enabled: import_prop_types.default.bool,
    fn: import_prop_types.default.func,
    name: import_prop_types.default.any,
    options: import_prop_types.default.object,
    phase: import_prop_types.default.oneOf(["afterMain", "afterRead", "afterWrite", "beforeMain", "beforeRead", "beforeWrite", "main", "read", "write"]),
    requires: import_prop_types.default.arrayOf(import_prop_types.default.string),
    requiresIfExists: import_prop_types.default.arrayOf(import_prop_types.default.string)
  })),
  /**
   * If `true`, the component is shown.
   */
  open: import_prop_types.default.bool.isRequired,
  /**
   * @ignore
   */
  ownerState: import_prop_types.default.any,
  /**
   * Popper placement.
   * @default 'bottom'
   */
  placement: import_prop_types.default.oneOf(["auto-end", "auto-start", "auto", "bottom-end", "bottom-start", "bottom", "left-end", "left-start", "left", "right-end", "right-start", "right", "top-end", "top-start", "top"]),
  /**
   * Options provided to the [`Popper.js`](https://popper.js.org/docs/v2/constructors/#options) instance.
   * @default {}
   */
  popperOptions: import_prop_types.default.shape({
    modifiers: import_prop_types.default.array,
    onFirstUpdate: import_prop_types.default.func,
    placement: import_prop_types.default.oneOf(["auto-end", "auto-start", "auto", "bottom-end", "bottom-start", "bottom", "left-end", "left-start", "left", "right-end", "right-start", "right", "top-end", "top-start", "top"]),
    strategy: import_prop_types.default.oneOf(["absolute", "fixed"])
  }),
  /**
   * A ref that points to the used popper instance.
   */
  popperRef: refType_default,
  /**
   * The props used for each slot inside the Popper.
   * @default {}
   */
  slotProps: import_prop_types.default.shape({
    root: import_prop_types.default.oneOfType([import_prop_types.default.func, import_prop_types.default.object])
  }),
  /**
   * The components used for each slot inside the Popper.
   * Either a string to use a HTML element or a component.
   * @default {}
   */
  slots: import_prop_types.default.shape({
    root: import_prop_types.default.elementType
  }),
  /**
   * The system prop that allows defining system overrides as well as additional CSS styles.
   */
  sx: import_prop_types.default.oneOfType([import_prop_types.default.arrayOf(import_prop_types.default.oneOfType([import_prop_types.default.func, import_prop_types.default.object, import_prop_types.default.bool])), import_prop_types.default.func, import_prop_types.default.object]),
  /**
   * Help supporting a react-transition-group/Transition component.
   * @default false
   */
  transition: import_prop_types.default.bool
} : void 0;
var Popper_default = Popper;

export {
  Popper_default
};
//# sourceMappingURL=chunk-A7HT3P54.js.map

The styled here is mui-material/src/styles/styled.js

import { createStyled, shouldForwardProp } from '@mui/system';
import defaultTheme from './defaultTheme';

export const rootShouldForwardProp = (prop) => shouldForwardProp(prop) && prop !== 'classes';

export const slotShouldForwardProp = shouldForwardProp;

const styled = createStyled({
  defaultTheme,
  rootShouldForwardProp,
});

export default styled;

Full transformed code by vite:

import {
  createStyled,
  defaultTheme_default,
  init_defaultTheme,
  init_esm,
  shouldForwardProp,
  useThemeProps
} from "/node_modules/.vite/deps/chunk-M6YZV643.js?v=b24550c9";
import {
  __esm
} from "/node_modules/.vite/deps/chunk-AC2VUBZ6.js?v=b24550c9";

// node_modules/@mui/material/styles/useThemeProps.js
function useThemeProps2({
  props,
  name
}) {
  return useThemeProps({
    props,
    name,
    defaultTheme: defaultTheme_default
  });
}
var init_useThemeProps = __esm({
  "node_modules/@mui/material/styles/useThemeProps.js"() {
    init_esm();
    init_defaultTheme();
  }
});

// node_modules/@mui/material/styles/styled.js
var rootShouldForwardProp, slotShouldForwardProp, styled, styled_default;
var init_styled = __esm({
  "node_modules/@mui/material/styles/styled.js"() {
    init_esm();
    init_defaultTheme();
    rootShouldForwardProp = (prop) => shouldForwardProp(prop) && prop !== "classes";
    slotShouldForwardProp = shouldForwardProp;
    styled = createStyled({
      defaultTheme: defaultTheme_default,
      rootShouldForwardProp
    });
    styled_default = styled;
  }
});

export {
  useThemeProps2 as useThemeProps,
  init_useThemeProps,
  rootShouldForwardProp,
  slotShouldForwardProp,
  styled_default,
  init_styled
};
//# sourceMappingURL=chunk-QGFUN55Y.js.map

Note that in the styled module, styled need to be initialized by createStyled:

// node_modules/@mui/material/styles/styled.js
var rootShouldForwardProp, slotShouldForwardProp, styled, styled_default;
var init_styled = __esm({
  "node_modules/@mui/material/styles/styled.js"() {
    init_esm();
    init_defaultTheme();
    rootShouldForwardProp = (prop) => shouldForwardProp(prop) && prop !== "classes";
    slotShouldForwardProp = shouldForwardProp;
    styled = createStyled({
      defaultTheme: defaultTheme_default,
      rootShouldForwardProp
    });
    styled_default = styled;
  }
});

export {
  useThemeProps2 as useThemeProps,
  init_useThemeProps,
  rootShouldForwardProp,
  slotShouldForwardProp,
  styled_default,
  init_styled
};

This suggest we should call init_styled prior to access styled_default. But such an assertion is failing in Popper:

import {
  PopperUnstyled_default,
  init_PopperUnstyled
} from "/node_modules/.vite/deps/chunk-73GXGH6W.js?v=b24550c9";
import {
  styled_default,
  useThemeProps
} from "/node_modules/.vite/deps/chunk-QGFUN55Y.js?v=b24550c9";
import {
  init_esm as init_esm2,
  useThemeWithoutDefault_default
} from "/node_modules/.vite/deps/chunk-M6YZV643.js?v=b24550c9";
import {
  _objectWithoutPropertiesLoose,
  init_objectWithoutPropertiesLoose
} from "/node_modules/.vite/deps/chunk-KBFHYFJ6.js?v=b24550c9";
import {
  HTMLElementType,
  init_esm,
  refType_default
} from "/node_modules/.vite/deps/chunk-KQS6UZBQ.js?v=b24550c9";
import {
  require_prop_types
} from "/node_modules/.vite/deps/chunk-EOOR7TYC.js?v=b24550c9";
import {
  require_jsx_runtime
} from "/node_modules/.vite/deps/chunk-TNQUW4IY.js?v=b24550c9";
import {
  _extends,
  init_extends
} from "/node_modules/.vite/deps/chunk-6K2CSZVE.js?v=b24550c9";
import {
  require_react
} from "/node_modules/.vite/deps/chunk-JFTBQ7A7.js?v=b24550c9";
import {
  __toESM
} from "/node_modules/.vite/deps/chunk-AC2VUBZ6.js?v=b24550c9";

// node_modules/@mui/material/Popper/Popper.js
init_extends();
init_objectWithoutPropertiesLoose();
init_PopperUnstyled();
init_esm2();
init_esm();
var import_prop_types = __toESM(require_prop_types());
var React = __toESM(require_react());
var import_jsx_runtime = __toESM(require_jsx_runtime());
var _excluded = ["components", "componentsProps", "slots", "slotProps"];
var PopperRoot = styled_default(PopperUnstyled_default, {
  name: "MuiPopper",
  slot: "Root",
  overridesResolver: (props, styles) => styles.root
})({});

Missing calling of init_styled from chunk-QGFUN55Y.js (the chunk of styled)

import {
  styled_default,
  useThemeProps
  // init_styled missing
} from "/node_modules/.vite/deps/chunk-QGFUN55Y.js?v=b24550c9";

// missing calling of init_styled();

// styled_default is undefined.
var PopperRoot = styled_default(/*  */)

@Tanimodori
Copy link

This can be verified using

import("http://localhost:5173/node_modules/.vite/deps/chunk-QGFUN55Y.js?v=b24550c9").then(module =>{
  console.log(module.styled_default)
  module.init_styled();
  console.log(module.styled_default)
})

image

@Tanimodori
Copy link

Tanimodori commented Mar 16, 2023

I think this bug may related to chunk seperation. When such a small chunk of styled is generated, this bug will occur. When a big chunk like the whole @mui/material, the initialization will be correct because they have been merged:

node_modules/.vite/deps/@mui_material.js (Whole big dep chunk of @mui/material)

// at line number 33000-ish

// node_modules/@mui/material/styles/styled.js
var rootShouldForwardProp = (prop) => shouldForwardProp(prop) && prop !== "classes";
var slotShouldForwardProp = shouldForwardProp;
var styled3 = createStyled3({
  defaultTheme: defaultTheme_default,
  rootShouldForwardProp
});
var styled_default2 = styled3;

@Tanimodori
Copy link

So this comment is true on the aspects of this issue

It seems to be:

  1. Related to using Vite.
  2. Intermittent, the problem comes and goes.
  3. Resolved (sometimes) by pnpm prune or removing node_modules folders
  1. It is related to vite dep pre-bundle. It is a vite-only bug.
  2. It is related how vite generate deps, big dep chunks are fine but small ones are problematic. Fresh cloned repo seems to be efficient trigger vite small deps generation.
  3. It touches node_modules and triggers vite to re-generate deps. Vite seems to be more likely to generate big dep chunks after the first generation. So when people installing/uninstalling deps, this issue tends to be "fixed".

@bnabet
Copy link

bnabet commented Mar 16, 2023

Hello, for information, I am facing the same problem when using the Card component.

@Nefcanto
Copy link
Author

@Tanimodori thank you for spending time on this. So it's a Vite bug. I'm glad that you could find the bug. It was such a complicated situation.

@Tanimodori
Copy link

Maybe related: #5142

@ashutosh887

This comment was marked as resolved.

@patak-dev

This comment was marked as resolved.

@ashutosh887

This comment was marked as resolved.

@patak-dev

This comment was marked as resolved.

@jbsouvestre
Copy link

Hey all, I've been trying to fix what I believe is a very similar issue, except for me it affects the @mui/x-date-pickers.

I'm having the error Uncaught TypeError: useEnhancedEffect_default is not a function only when building the app
What leads me to believe the issue is related is because of this issue in the mui repo: mui/material-ui#31835 which seems similar to what is described here

While working on a minimal reproduction, it seems like the bug exists in version 4.0.0 of vite, but is resolved in 4.2.0

Please find an attached repository example: https://github.com/jbsouvestre/vite-esbuild-bug-repro
There's 2 branches, master is on vite@4.2.0, the production build doesn't have the error

The vite-4.0.0 branch has the bug

image

If the issue is not related, please disregard this comment

@Tanimodori
Copy link

@jbsouvestre The vite version I used for my analysis is 4.2.0 fyi.

@stephdotnet
Copy link

I'm also having this issue (on Box.js with the following error : Uncaught TypeError: createTheme_default is not a function)
I suspect an issue with small chunks since no problem with building the app, and what solved it for me was to change the import of my MUi components as indicated in the comment mui/material-ui#31835 (comment)

@mtgeddes
Copy link

mtgeddes commented Apr 10, 2023

I'm having the same issue but with Grid2

Uncaught TypeError: styled_default is not a function
    at Grid2.js:5:26
(anonymous) @ Grid2.js:5

Update: I managed to have the error moved onto Box.js as mentioned in the comment above when I rearranged import order.

I was finally successful in removing the error altogether after further import order rearrangements. I essentially started at my top-level app file and moved a few (not all) material component imports to the top. It seemed to like it when custom components that also use MUI components were imported after MUI components used in the immediate file.

Luckily, I didn't have to continue that process into other files as my fix was in a top level file.

@joaovieirabr
Copy link

joaovieirabr commented Apr 12, 2023

Same Issue with Grid2

But caused by upgrading "@mui/x-data-grid" to 6.1.0. The bug doesn't happen on 5.x versions;
id2.js:5 Uncaught TypeError: styled_default is not a function at Grid2.js:5:26 (

Update:
I removed @mui/x-data-grid, and the app run; When I put it back, without any reference - only in package.json/yarn.lock, the bug came back. So, isn't seems to be the order of imports.

@crummy
Copy link

crummy commented Apr 23, 2023

I had the popper.js error but it has disappeared after upgrading Vite from 4.1.1 to 4.3.1.

edit: it's back. This issue is popping up daily for at least someone on my team.

edit again: I got rid of <Popper> in our codebase and replaced it with <Modal>.

@joespeargresham
Copy link

joespeargresham commented Apr 26, 2023

We're also experiencing this issue. Upgrading Vite hasn't worked. It mostly seems to effect us when using icons from the @mui/icons-material package, but haven't figured out a pattern yet as we use icons all over the place and some seem to work and some don't.

@Takouaghouaiel
Copy link

hello i have the same problem here :
Screenshot 2023-04-27 113808
I even didnt' use popper ! please any help ?

@igomonteiro
Copy link

igomonteiro commented Apr 27, 2023

Same problem here, I cant use popper, getting the error:

caught TypeError: styled_default is not a function
   at Popper.js:11:20

I'm using vite, npm and styled-components.

@jmelendez-cbs
Copy link

Has anyone had any success with a temporary work around? Im using NX and Vite@4.1.1 and this has been a blocker for the past 4 days.

@tjosgood
Copy link

tjosgood commented May 2, 2023

Using
Vite v4.3.3
MUI v5.12
@mui/x-data-grid-pro v6

Also having same issue in Grid2.js

Uncaught TypeError: styled_default is not a function
    at Grid2.js:5:26
(anonymous) @ Grid2.js:5

Seems to happen after a few restart cycles, usually clearing node_modules and npm install makes it go away for a while but not a great solution.

Was there some logic to the re-ordering of imports that seems to work? Moving Mui imports higher doesnt seem to have any effect for me

@paulczy
Copy link

paulczy commented May 2, 2023

I upgraded to notistack v3.x I started to get the same error:

Uncaught TypeError: styled_default is not a function
    at Grid2.js:5:26

When fall back to notistack 2.0.8 it goes away.

vite 4.3.3
vitejs/plugin-react-swc 3.3.0
mui 5.12.1
mui/x-data-grid-premium 6.2.1

@w-ap-admin
Copy link

We encounter the same problem on our project. And we are not able to reproduce systematically the error. We already try to upgrade or downgrade MUI, we check every import. Everything seems right, but sometimes, the appears, sometimes it works perfectly.

@rene-stesl
Copy link

rene-stesl commented May 9, 2023

I have the same Issue after updating only vite-plugin-checker from 0.5.6 to 0.6.0
Same happens if I only update @vitejs/plugin-react from 3.1.0 to 4.0.0

Uncaught TypeError: styled_default is not a function
    at Popper.js:11:20

@nzhiti
Copy link

nzhiti commented May 9, 2023

It doesn't seem related to vitejs version since we have same issue with vite 3.1.0
However, I've the feeling that I might bundling two versions of emotion/styled since @mui has a peer depency on emotion/styled 11.3.0 and x-date-pickers has a peer dependency on emotion/styled 11.8.1

Could it be the issue ?

@Methuselah96
Copy link

@Tanimodori Thanks for the excellent investigation work.

I've narrowed down the issue a bit more and created an esbuild issue: evanw/esbuild#3357.

@ShahmirzeMIT
Copy link

This error happened to me after that I updated npm and then fixed it

@Madebyspeedster
Copy link

This has worked for us. mui/material-ui#32727 (comment)

This worked for me as well.

Basically if you have issues with Popper.js

add to vite.config.js

optimizeDeps: {
  include: ['@mui/material/Tooltip'],
};

If it's not Popper.js find the relevant component and include it as an optimized dep.

oh, this is saved my day!

image

@Ronnin1994
Copy link

Almost a year and the issue is still there...Can't work.

@ShahmirzeMIT
Copy link

ShahmirzeMIT commented Mar 11, 2024 via email

@javaspeak
Copy link

javaspeak commented Mar 15, 2024

Almost a year and the issue is still there...Can't work.

I have the same error and when I get it I can only solve the problem by deleting node_modules and running npm install again.

@Methuselah96
Copy link

Because the issue is with the cached dependencies built by esbuild, deleting node_modules/.vite instead of all of node_modules may also work, which would make it so that you don't have to run npm install again.

@javaspeak
Copy link

Because the issue is with the cached dependencies built by esbuild, deleting node_modules/.vite instead of all of node_modules may also work, which would make it so that you don't have to run npm install again.

Thanks. I followed the recommendation above of adding this to vite.config.js

optimizeDeps: {
include: ['@mui/material/Tooltip'],
};

and it seems to have done the trick - not sure if this is permanently fixed or just by chance.

@nafissalabdi
Copy link

I encountered the same error and resolved it by installing 'esbuild'.

You can try this command: 'npm install --save-exact --save-dev esbuild'

@Loschcode
Copy link

Also experiencing the problem, is anyone working on that? It's a big problem for many people it seems

@AresEkb
Copy link

AresEkb commented Apr 27, 2024

I've tried all of the recipes without any success. And I think I've found a stable workaround. Just add

import '@mui/material/styles/styled';

as a first statement in your index.tsx file (or other file). It should be the first import.

It propely initalizes styled function, so it can be used later.

Remove cache folder node_modules/.vite and restart your application.

If you have a complicated multi-module application and it's unclear to wich module you should add this import, then you can try the following algorithm:

  1. For instance you get error "Uncaught TypeError: styled_default is not a function at chunk-54HMABV7.js?v=1f2b2aed:99:18"
  2. Open Network tab in Chrome DevTools and filter requests by chunk-54HMABV7.js
  3. You will see a GET request of that file
  4. In column Initiator you will see a script importing the file. Let it be @mui_material_Tooltip.js?v=9a4fee34
  5. Filter network requests again by @mui_material_Tooltip.js
  6. Look at Initiator column. Let it be web-application.es.js:50
  7. If it's a script from an extenral library (not your application) then repeat the above steps
  8. If it's your script then at the beginnig of the file add import '@mui/material/styles/styled';

@minjeCoding
Copy link

minjeCoding commented May 20, 2024

If you use Tooltip of mui, please refer this.

Hello, I'm a junior developer in my second year working in South Korea.
I hope you guys resolve this problem by this below.

When starting the development server with npm run dev, Vite pre-bundles dependency modules (including many dependencies like the MUI library) to improve loading speed. The results of this bundling are generated as several chunk_????.js files inside the 'node_modules/.vite/deps' directory.

If Vite correctly pre-bundles, no error occurs.

Although it seems odd that the pre-bundling works correctly in some local environments and causes errors in others, the following is clear:

In environments where the error occurs, adding the following option to vite.config.js will ensure Vite includes this correctly in the pre-bundle:

optimizeDeps: {
    include: ['@mui/material/Tooltip'],
}

By explicitly telling Vite to optimize (pre-bundle) this, the error can be avoided.
I resolved our team's issue using this method. Hopefully, it will bring the same results for everyone else.

@pailhead
Copy link

The include solution did not work for me, importing this package explicitly in my index file did.

@J-cyber-d
Copy link

image
Iam Integrate an microfront-end in mani app , here Iam getting this issue the below is an code for micro-app1
`import { useEffect, useState } from "react";
import EditIcon from "@mui/icons-material/Edit";
import {
Box,
Button,
// CircularProgress,
IconButton,
Stack,
Typography,
Table,
TableBody,
TableCell,
TableContainer,
TableHead,
TableRow,
// Tooltip,
} from "@mui/material";
import DeletePopup from "../helpers/DeletePopup";
import axios from "axios";
import Alerts from "../helpers/Alerts";
import logger from "../../utils/logger";
// import DataNotFount from "../helpers/DataNotFount";
import AssetFormDialog from "./AddFrom";

const API_URL = import.meta.env.VITE_APP_API_URL;

interface Asset {
_id: string;
Category: string;
PurchaseDate: string;
AssetName: string;
SerialNumber: string;
ModelNumber: string;
PurchaseCost: number;
Status: string;
}

const TableComponent: React.FC = () => {
const [openForm, setOpenForm] = useState(false);
const [updateData, setUpdateData] = useState<Asset | string>("");
const [updateId, setUpdateId] = useState("");
const [update, setUpdate] = useState(false);
const [assetInfo, setAssetInfo] = useState<Asset[]>([]);
const [snackAdd, setSnackAdd] = useState(false);
const [loading, setLoading] = useState(false);
console.log(loading);

const [reloading, setReloading] = useState(false);
const [alert, setAlert] = useState({
open: false,
message: "",
severity: "",
});

const handleDelete = (id: string) => async () => {
console.info("Delete Request");
try {
setReloading(true);

  setTimeout(async () => {
    const response = await axios.delete(`${API_URL}/assets/${id}`);

    if (response.status === 200) {
      console.log("Asset deleted successfully");
    } else {
      console.error("Failed to delete asset");
    }
    setAlert({
      open: true,
      message: "Assets Deleted successfully",
      severity: "success",
    });
    setReloading(false);
  }, 1000);
} catch (error) {
  console.error("An error occurred:", error);
  setReloading(false);
}

};

const handleUpdateData = async (id: string) => {
try {
const response = await axios.get(${API_URL}/assets/${id});
console.info("Asset data fetched successfully");

  setUpdateData(response.data);
  setOpenForm(true);
  setUpdateId(id);
  setUpdate(true);
} catch (err) {
  console.error("Failed to get data: " + err);
}

};

useEffect(() => {
let timer: any;

const getData = async () => {
  setLoading(true);
  timer = setTimeout(async () => {
    try {
      const apidata = await fetch(`${API_URL}/assets`);
      const response = await apidata.json();
      setAssetInfo(response);
      logger.info("Asset get successful");
      setLoading(false);
    } catch (error) {
      console.error("Error fetching asset data:", error);
      setLoading(false);
    }
  }, 1500);
};

getData();
return () => clearTimeout(timer);

}, [reloading]);

function DateFormat(dateString: string): string {
const date = new Date(dateString);

if (isNaN(date.getTime())) {
  return dateString;
}

const month = new Intl.DateTimeFormat("en-US", { month: "short" }).format(
  date
);
const day = new Intl.DateTimeFormat("en-US", { day: "numeric" }).format(
  date
);
const year = new Intl.DateTimeFormat("en-US", { year: "numeric" }).format(
  date
);
return `${day}-${month}-${year}`;

}

function AmountFormat(amount: number): string {
return new Intl.NumberFormat("en-US", {
style: "currency",
currency: "USD",
}).format(amount);
}

const handleFormOpen = () => {
setOpenForm(true);
setUpdate(false);
logger.info("Asset Add button click");
setUpdateData("");
};

const handleCloseAlert = () => {
setAlert({
open: false,
message: "",
severity: "",
});
};

const [isActive, setIsActive] = useState(true);

useEffect(() => {
let timer: any;
if (isActive) {
timer = setTimeout(() => {
setIsActive(false);
}, 2000);
}

return () => clearTimeout(timer);

}, [isActive]);

return (
<>




<Box
sx={{
display: "flex",
justifyContent: "space-between",
mx: 5,
mt: 2,
}}>
<Typography
variant="h6"
component="div"
sx={{
fontWeight: "bold",
fontSize: "1.2rem",
}}>
Assets

<Button
onClick={handleFormOpen}
type="submit"
variant="contained"
color="primary"
id="add-expenses-btn"
sx={{ textTransform: "none" }}>
Add Asset

  {/* {isActive ? (
    <Box sx={{ textAlign: "center", my: 1 }}>
      <CircularProgress />
    </Box>
  ) : assetInfo.length > 0 ? ( */}
  <TableContainer sx={{ mt: 5 }}>
    <Table sx={{ minWidth: 650 }} size="small" aria-label="purchases">
      <TableHead sx={{ bgcolor: "#1976D2", p: "0px" }}>
        <TableRow>
          <TableCell sx={{ color: "white" }}>Category</TableCell>
          <TableCell align="center" sx={{ color: "white" }}>
            Purchase Date
          </TableCell>
          <TableCell sx={{ color: "white" }}>Asset</TableCell>
          <TableCell sx={{ color: "white" }}>Serial Number</TableCell>
          <TableCell sx={{ color: "white" }}>Model Number</TableCell>
          <TableCell align="right" sx={{ color: "white" }}>
            Purchase Cost
          </TableCell>
          <TableCell sx={{ color: "white" }}>Status</TableCell>
          <TableCell align="center" sx={{ color: "white" }}>
            Actions
          </TableCell>
        </TableRow>
      </TableHead>
      <TableBody>
        {assetInfo.map((item) => (
          <TableRow key={item._id}>
            <TableCell sx={{ py: "0px" }}>{item.Category}</TableCell>
            <TableCell sx={{ py: "0px" }} align="center">
              {DateFormat(item.PurchaseDate)}
            </TableCell>
            <TableCell sx={{ py: "0px" }}>{item.AssetName}</TableCell>
            <TableCell sx={{ py: "0px" }}>{item.SerialNumber}</TableCell>
            <TableCell sx={{ py: "0px" }}>{item.ModelNumber}</TableCell>
            <TableCell sx={{ py: "0px" }} align="right">
              {AmountFormat(item.PurchaseCost)}
            </TableCell>
            <TableCell sx={{ py: "0px" }}>{item.Status}</TableCell>
            <TableCell align="center" sx={{ py: "0px" }}>
              <Stack direction="row">
                {/* <Tooltip title="Edit"> */}
                <IconButton onClick={() => handleUpdateData(item._id)}>
                  <EditIcon
                    style={{ cursor: "pointer", fontSize: "22px" }}
                  />
                </IconButton>
                {/* </Tooltip> */}
                {/* <Tooltip title="Delete"> */}
                <IconButton>
                  <DeletePopup
                    handleDelete={handleDelete(item._id)}
                    name={item.AssetName}
                  />
                </IconButton>
                {/* </Tooltip> */}
              </Stack>
            </TableCell>
          </TableRow>
        ))}
      </TableBody>
    </Table>
  </TableContainer>
  {/* ) : (
    <DataNotFount title="Please add new Assets" />
  )} */}

  <AssetFormDialog
    open={openForm}
    handleClose={() => setOpenForm(false)}
    setSnackAdd={setSnackAdd}
    snackAdd={snackAdd}
    setOpenForm={setOpenForm}
    updateId={updateId}
    updateData={updateData}
    update={update}
    setReloading={setReloading}
    setAlert={setAlert}
  />
</>

);
};

export default TableComponent;
**the above is getting error while use for module federation it is used in micro-front app1** vite.config.js file in micro-front app 1 import { defineConfig } from "vite";
import react from "@vitejs/plugin-react-swc";
import federation from "@originjs/vite-plugin-federation";

// https://vitejs.dev/config/
export default defineConfig({
optimizeDeps: {
include: ["@mui/material/Tooltip"],
},
plugins: [
react(),
federation({
name: "ipx-ams-web",
filename: "remoteEntry.js",
exposes: {
"./AssestManagement": "./src/Components/marcho/Table",
},
shared: ["react", "react-dom", "react-router-dom"],
}),
],
build: {
modulePreload: true,
target: "esnext",
minify: false,
cssCodeSplit: true,
},
// server: {
// port: 3000,
// open: true,
// },
// resolve: {
// alias: {
// "@": path.resolve(__dirname, "src"),
// },
// },
// css: {
// preprocessorOptions: {
// less: {
// javascriptEnabled: true,
// },
// },
// },
// esbuild: {
// jsxInject: import React from 'react',
// },
// optimizeDeps: {
// include: ["@ant-design/icons"],
// },
});
`

@kashanghori
Copy link

I've tried all of the recipes without any success. And I think I've found a stable workaround. Just add

import '@mui/material/styles/styled';

as a first statement in your index.tsx file (or other file). It should be the first import.

It propely initalizes styled function, so it can be used later.

Remove cache folder node_modules/.vite and restart your application.

If you have a complicated multi-module application and it's unclear to wich module you should add this import, then you can try the following algorithm:

  1. For instance you get error "Uncaught TypeError: styled_default is not a function at chunk-54HMABV7.js?v=1f2b2aed:99:18"
  2. Open Network tab in Chrome DevTools and filter requests by chunk-54HMABV7.js
  3. You will see a GET request of that file
  4. In column Initiator you will see a script importing the file. Let it be @mui_material_Tooltip.js?v=9a4fee34
  5. Filter network requests again by @mui_material_Tooltip.js
  6. Look at Initiator column. Let it be web-application.es.js:50
  7. If it's a script from an extenral library (not your application) then repeat the above steps
  8. If it's your script then at the beginnig of the file add import '@mui/material/styles/styled';

This seems to work for me , thanks

@Rashad-Muntar
Copy link

Rashad-Muntar commented Sep 5, 2024

This worked for me for VITS project.

  1. I remove the .vit directory from the node_modules
  2. The restarted the project.

All worked fine

@cmdcolin
Copy link

cmdcolin commented Nov 3, 2024

am I correct that this bug is in the dev-mode of vite only (so not in production builds)?

aside: I think I found a similar issue with @mui/icons-material here mui/material-ui#44180

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug: upstream Bug in a dependency of Vite feat: deps optimizer Esbuild Dependencies Optimization
Projects
None yet
Development

Successfully merging a pull request may close this issue.