vercel / next.js

The React Framework
https://nextjs.org
MIT License
125.78k stars 26.85k forks source link

ESM build with standalone output and custom directory outputs CommonJS code instead of ESM #62521

Open zollf opened 7 months ago

zollf commented 7 months ago

Link to the code that reproduces this issue

https://github.com/zollf/nextjs-standalone-esm-bug

To Reproduce

  1. Add "type": "module" in package.json for ESM
  2. Add output: 'standalone' in next config
  3. Rename or add a custom directory to build from
  4. Build using custom directory npm run build custom-dir
  5. Run standalone server node custom-dir/.next/standalone/custom-dir/server.js

Current vs. Expected behavior

When trying to run a standalone server it will result in a reference error:ReferenceError: require is not defined in ES module scope, you can use import instead. Upon inspection server.js is using CommonJS, not ESM code.

Looking at the build utils this potentially could be the cause:

https://github.com/vercel/next.js/blob/bef716ad031591bdf94058aaf4b8d842e75900b5/packages/next/src/build/utils.ts#L1948-L1950

Our package.json location is one more directory away.

The expected outcome is for standalone output to be ESM code with a custom directory

Provide environment information

Operating System:
  Platform: darwin
  Arch: arm64
  Version: Darwin Kernel Version 23.1.0: Mon Oct  9 21:28:31 PDT 2023; root:xnu-10002.41.9~6/RELEASE_ARM64_T8112
Binaries:
  Node: 18.17.1
  npm: 9.6.7
  Yarn: 1.22.21
  pnpm: N/A
Relevant Packages:
  next: 14.1.0
  eslint-config-next: N/A
  react: 18.2.0
  react-dom: 18.2.0
  typescript: 5.3.3
Next.js Config:
  output: standalone

Which area(s) are affected? (Select all that apply)

Module resolution (CJS / ESM, module resolving)

Which stage(s) are affected? (Select all that apply)

next build (local)

Additional context

No response

DavieReid commented 1 month ago

Have you found a workaround for this issue? I am using a monorepo (turbo with pnpm workspaces) and I have the same problem.

zollf commented 1 month ago

Have you found a workaround for this issue? I am using a monorepo (turbo with pnpm workspaces) and I have the same problem.

@DavieReid We've just placed this package.json

{
  "type": "module"
}

in all our project folders.

DavieReid commented 1 month ago

Have you found a workaround for this issue? I am using a monorepo (turbo with pnpm workspaces) and I have the same problem.

@DavieReid We've just placed this package.json


{

  "type": "module"

}

in all our project folders.

Thanks, I am doing pretty much the same thing.