vercel / next.js

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

Dynamic `import()` function usage behaves strangely, prevents server-only code #69070

Open coreyward opened 2 months ago

coreyward commented 2 months ago

Link to the code that reproduces this issue

https://codesandbox.io/p/devbox/relaxed-gagarin-khcz7s

To Reproduce

The following code executes fine in Node, but it causes a "Module Not Found" error in Next.js:

export default function Home() {
  return "Hello, world!";
}

// This function is never called
const example = () => {
  return false;

  // This code is inaccessible
  import("any import, but for the sake of the demo, a path that doesn't exist");
};
Screenshot 2024-08-19 at 2 14 53 PM

Current vs. Expected behavior

You can copy the example function definition into Node and not only does the function get defined, but you can run it and you will get a false value in return. No errors, because we haven't done anything to trigger one. That is what I would expect to happen here.

What is actually instead is confusing, but I suspect is related to ensuring dynamically imported code is available client side. Unfortunately, this prevents the use of dynamic imports to split code in a way that allows me to keep server-only code server side because all dynamic imports are resolved and bundled by Next.js, even if there is a conditional guarding the import on the client.

Provide environment information

Node 20.x
Next 14.25 or 15 Canary
See reproduction for any other required details.

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

Developer Experience, Lazy Loading, Module Resolution, Output (export/standalone), Pages Router

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

next dev (local), next build (local)

Additional context

No response

akjadhav commented 2 months ago

Did some tracing in the code - seems to be that the code is being compiled by webpack and webpack is importing all dynamic imports. A fix would need to alter how webpack is compiling the code or do some type of handling for this.