In my current project, which utilizes the Nx monorepo environment combined with Next.js, I've encountered an issue related to ES modules. The problem is specifically tied to the Swiper.js library.
After the Swiper.js library was updated and switched to using ES module format, difficulties arose when transitioning to pages where this library is used. The errors are as follows:
Error: require() of ES Module lalala… swiper/modules/index.mjs not supported.
Instead change the require of lalala… /swiper/modules/index.mjs to a dynamic import() which is available in all CommonJS modules.
One workaround I found is to add an exclamation mark before the import, as shown below, to exclude this module from transpilation. Although this works, I don't consider it a good solution, and it forces me to mock all these components in tests :
import { Swiper, SwiperSlide } from '!swiper/react'
I also tried excluding the Swiper library from the transpilation process in the webpack configuration, but it didn't yield positive results (perhaps I did it incorrectly given the project's intricacies).
Perhaps someone has ideas for solving this problem using webpack or other approaches?
I've also prepared a test repository to reproduce this issue. To do so, simply clone the repository, run npm install, and then nx serve nextjs. After that, click the "GO TO ABOUT" link on the opened page (as it contains the Swiper.js import).
Repository Link: https://github.com/bulletbrand/swiper/
Important to note that this problem only occurs when running through a custom Next.js server. If you check the workspace.json in the monorepo root, you'll see the line "customServerPath": "/src/server.ts"
, which is the runner.
If you need any more details regarding the issue, feel free to ask.