| 1 | --- |
| 2 | title: Prefer Statically Analyzable Paths |
| 3 | impact: HIGH |
| 4 | impactDescription: avoids accidental broad bundles and file traces |
| 5 | tags: bundle, nextjs, vite, webpack, rollup, esbuild, path |
| 6 | --- |
| 7 | |
| 8 | ## Prefer Statically Analyzable Paths |
| 9 | |
| 10 | Build tools work best when import and file-system paths are obvious at build time. If you hide the real path inside a variable or compose it too dynamically, the tool either has to include a broad set of possible files, warn that it cannot analyze the import, or widen file tracing to stay safe. |
| 11 | |
| 12 | Prefer explicit maps or literal paths so the set of reachable files stays narrow and predictable. This is the same rule whether you are choosing modules with `import()` or reading files in server/build code. |
| 13 | |
| 14 | When analysis becomes too broad, the cost is real: |
| 15 | |
| 16 | - Larger server bundles |
| 17 | - Slower builds |
| 18 | - Worse cold starts |
| 19 | - More memory use |
| 20 | |
| 21 | ### Import Paths |
| 22 | |
| 23 | **Incorrect (the bundler cannot tell what may be imported):** |
| 24 | |
| 25 | ```ts |
| 26 | const PAGE_MODULES = { |
| 27 | home: "./pages/home", |
| 28 | settings: "./pages/settings", |
| 29 | } as const; |
| 30 | |
| 31 | const Page = await |
| 32 | ``` |
| 33 | |
| 34 | **Correct (use an explicit map of allowed modules):** |
| 35 | |
| 36 | ```ts |
| 37 | const PAGE_MODULES = { |
| 38 | home: () => |
| 39 | settings: () => |
| 40 | } as const; |
| 41 | |
| 42 | const Page = await |
| 43 | ``` |
| 44 | |
| 45 | ### File-System Paths |
| 46 | |
| 47 | **Incorrect (a 2-value enum still hides the final path from static analysis):** |
| 48 | |
| 49 | ```ts |
| 50 | const baseDir = path |
| 51 | ``` |
| 52 | |
| 53 | **Correct (make each final path literal at the callsite):** |
| 54 | |
| 55 | ```ts |
| 56 | const baseDir = |
| 57 | kind === ContentKind. |
| 58 | ? path.join( |
| 59 | : path.join( |
| 60 | ``` |
| 61 | |
| 62 | In Next.js server code, this matters for output file tracing too. `path.join(process.cwd(), someVar)` can widen the traced file set because Next.js statically analyze `import`, |
| 63 | |
| 64 | Reference: [Next.js output](https://nextjs.org/docs/app/api-reference/config/next-config-js/output |