How Next.js support ESM and the building process?

258 Views Asked by At

Next.js 12 supports native ESM support. I would like to understand how Next.js supports ESM and the bundling process. The research process has not been smooth, so I would appreciate it if you could take a look at my understanding below to see if I have any misunderstandings. Thank you.

  1. Due to the incomplete browser support for CJS and ESM syntax, Next.js needs to bundle the code. My understanding is that for third-party packages, Next.js determines whether to use ESM or CJS based on the package.json file. For our own code, it looks at the type field under package.json or the file extensions (.mjs, .mts, .js, .ts, .cjs, .cts)

  2. If point 1 is correct, one advantage of ESM over CJS is that the file size is smaller. Based on my own testing, packages installed in Next.js in ESM format do indeed have a smaller bundle size compared to the CJS version. In other words, even though both are compiled for browser execution, the resulting bundle size will differ based on whether the original format was ESM or CJS.

  3. If point 2 is correct, this means that for a new project, if possible, the type under package.json should be set to module. However, if there are dependencies that only support CJS, we should still set them as commonjs. If feasible, the file extensions for our own code should primarily be .mjs or .mts.

  4. When the type in package.json is set to its default value (commonjs), importing an ESM package in .js or .ts files will have a difference compared to importing the same package but in its CJS version for Next.js. The resulting bundle size will be smaller when using the ESM version.

  5. If point 4 is correct, it's because starting from Next.js 12, which supports ESM, that we can now import packages that only support ESM and reap some benefits.

  6. tsconfig.json does not affect the Next.js bundling; it is specifically for type checking.

During this transition period, there will be a situation of mixing ESM and CJS. I really want to understand the logic behind this and if there are any best practices to follow. Thank you for your help.

0

There are 0 best solutions below