Resolve relative imports in `next.config.ts` from the config directory (#99743)
### What? Relative imports in `next.config.ts` resolve against `process.cwd()` instead of the config file's directory. Building or starting a project from any other directory (for example `next build app` from a monorepo root, or a tool that calls `loadConfig` for a project) either fails with `Cannot find module './...'`, or, if a file happens to exist at the same relative path under the working directory, silently loads that file instead. ### Why? With the default SWC loader, the compiled config is loaded by `requireFromString` in `packages/next/src/build/next-config-ts/require-hook.ts`. It creates a `Module` and sets `paths`, but never sets `filename`. `new Module(id, parent)` only sets `id`, and `_compile` does not set `filename`. When the parent module has no filename, Node's `Module._resolveLookupPaths` resolves relative requests against `'.'`, which is `process.cwd()`. `m.paths` only covers bare package lookups, which is why `node_modules` imports keep working. ### How? Set `m.filename = filename` before `m._compile(...)`, so relative requires resolve from `dirname(filename)`, the project directory. ### Tests Added `test/unit/isolated/next-config-ts-relative-imports.test.ts` with fixtures under `test/unit/isolated/_resolvedata/`. It loads a `next.config.ts` that imports `./lib/origin` with three working directories: - the config directory (baseline, already passes) - a directory with no `./lib/origin` (failed before with `MODULE_NOT_FOUND`) - a directory with its own `./lib/origin` (before, loaded that file and returned `'cwd'` instead of `'config-dir'`) The test runs `loadConfig` in a child process. Under jest, `loadConfig` loads the config with `require()` (`__NEXT_TEST_MODE === 'jest'`) and never reaches `transpileConfig`, so an in-process test passes with or without the fix. The child process also gives each case its own working directory and module cache, and sets `__NEXT_NODE_NATIVE_TS_LOADER_ENABLED=false` to make sure the SWC path is exercised. Without the fix, 2 of the 3 tests fail; with it, all pass. The existing `test/unit/isolated/config.test.ts` and the `test/e2e/app-dir/next-config-ts/nested-imports` and `import-from-node-modules` suites still pass. Fixes #99742
Showing
Please
register
or
sign in
to comment