creativetimofficial / material-tailwind

@material-tailwind is an easy-to-use components library for Tailwind CSS and Material Design.
https://material-tailwind.com/
MIT License
3.51k stars 306 forks source link

Vite compatibility #671

Open mahmoudmoravej opened 2 months ago

mahmoudmoravej commented 2 months ago

I started using Material-tailwind + Remix + Vite, but I am getting the following errors. You can see it on Stackblitz.com

[vite] Named export 'Collapse' not found. The requested module '@material-tailwind/react' is a CommonJS module, which may not support all module.exports as named exports.
CommonJS modules can always be imported via the default export, for example using:

import pkg from '@material-tailwind/react';
const {Navbar, Typography, Button, IconButton, Collapse} = pkg;

so, I changed it to:

import { default as material } from "@material-tailwind/react";
const { Navbar, Typography, Button, IconButton, Collapse } = material;

and it didn't raise error, but see the following error in Chrome browser console:

Uncaught TypeError: Cannot destructure property 'Navbar' of 'material' as it is **undefined**.

I checked the dowloaded package(i.e. http://localhost:4000/node_modules/.vite/deps/@material-tailwind_react.js?v=a54f6275), I see this.

import {
  require_react
} from "/node_modules/.vite/deps/chunk-JK4Z5R5S.js?v=a54f6275";
import "/node_modules/.vite/deps/chunk-3E2CTVYY.js?v=a54f6275";
import "/node_modules/.vite/deps/chunk-VPJAWDW6.js?v=a54f6275";
import "/node_modules/.vite/deps/chunk-E4NC7P6T.js?v=a54f6275";
import "/node_modules/.vite/deps/chunk-MB75G5AI.js?v=a54f6275";
import "/node_modules/.vite/deps/chunk-6XGTAVP7.js?v=a54f6275";
import "/node_modules/.vite/deps/chunk-ZRJG7NCB.js?v=a54f6275";
import "/node_modules/.vite/deps/chunk-2EXEP7CN.js?v=a54f6275";
import "/node_modules/.vite/deps/chunk-WXXH56N5.js?v=a54f6275";
export default require_react();
//# sourceMappingURL=@material-tailwind_react.js.map

which is a bit confusing. Any help? I am a bit suspecious to something like this: https://github.com/vitejs/vite/issues/10612

cognvn commented 2 months ago

I have same problem with Remix and I'm able to fix it with:

export default defineConfig({
     plugins: [remix(), tsconfigPaths()],
+    legacy: { proxySsrExternalModules: true },
});

Read more at Vite docs


... but it only works on dev or ssr: false. Consider using vite-plugin-cjs-interop

mahmoudmoravej commented 2 months ago

Thanks @cognvn! Interestingly, using the legacy flag didn't help. But by checking the shared vite document, I noticed I only tested the first workaround, so I tried the second one (i.e. use import * as material from ...) and it worked! although it is for dev and it failed in production.

As you said, the proper workaround is using the vite-plugin-cjs-interop lib until Material-Tailwind build esm module output too.