Keep import paths static
Use literal import() calls and paths so the bundler sees every file.
Next.js Docsnextjs.org
Reference: Next.js output
From vercel-react-best-practices, rule bundle-analyzable-paths.
What import() can see
Pick the pages you route to, then press Build.
Path in a variableBad
import(PAGE_MODULES[pageName])Map of import()Good
PAGE_MODULES[pageName]()
What the server traces
Press Trace. Everything listed ships with the function.
Joined at runtimeBad
path.join(cwd, 'content/' + kind)Literal per branchGood
path.join(cwd, 'content/blog')const baseDir =
kind === ContentKind.Blog
? path.join(process.cwd(), 'content/blog')
: path.join(process.cwd(), 'content/docs')
Why it matters, pros and cons
Why it matters
A path the build can't read forces it to include every file it might be.
Pros
- Smaller bundles and traced output.
- Faster builds and cold starts.
- The allowed set is written down in one map.
Cons
- Each new page needs a map entry.
- Long ternaries for many paths get noisy.
- A plugin like dynamic-import-vars can cover globs.