Unverified Commit c632caf3 authored by Daniel Caspi's avatar Daniel Caspi Committed by GitHub

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
parent f1069947
......@@ -51,6 +51,9 @@ export function requireFromString(code: string, filename: string) {
const paths = (Module as any)._nodeModulePaths(dirname(filename))
const m = new Module(filename, module.parent!) as any
m.paths = paths
// Without a filename, Node.js resolves relative requires against
// process.cwd() instead of dirname(filename).
m.filename = filename
m._compile(code, filename)
return m.exports
}
// Same relative path as the fixture next to next.config.ts. It must never be
// loaded: relative imports in next.config.ts resolve from the config's
// directory, not from process.cwd().
export const origin = 'cwd'
import { origin } from './lib/origin'
export default {
__test__relativeImport: origin,
}
/* eslint-env jest */
import { spawnSync } from 'child_process'
import { join } from 'path'
import { PHASE_PRODUCTION_BUILD } from 'next/constants'
const resolveData = join(__dirname, '_resolvedata')
const configDir = join(resolveData, 'typescript-config-relative-import')
// Under jest, loadConfig() loads next.config.ts with jest's require() instead
// of transpileConfig(), so the SWC require hook is only exercised in a real
// Node.js process. A child process also gives each case its own cwd and a
// clean module cache.
function loadConfigFrom(cwd: string) {
const script = `
const loadConfig = require(${JSON.stringify(
require.resolve('next/dist/server/config')
)}).default
loadConfig(${JSON.stringify(PHASE_PRODUCTION_BUILD)}, ${JSON.stringify(
configDir
)}).then(
(config) => {
console.log('RESULT=' + JSON.stringify(config.__test__relativeImport))
},
(err) => {
console.error(err)
process.exit(1)
}
)
`
const env: NodeJS.ProcessEnv = {
...process.env,
// Force the SWC transpile path rather than Node.js native type stripping.
__NEXT_NODE_NATIVE_TS_LOADER_ENABLED: 'false',
}
delete env.__NEXT_TEST_MODE
const result = spawnSync(process.execPath, ['-e', script], {
cwd,
env,
encoding: 'utf8',
})
const match = /^RESULT=(.*)$/m.exec(result.stdout)
return {
status: result.status,
stderr: result.stderr,
value: match ? JSON.parse(match[1]) : undefined,
}
}
describe('next.config.ts relative imports', () => {
it('should resolve relative imports when cwd is the config directory', () => {
const result = loadConfigFrom(configDir)
expect(result.stderr).not.toContain('Cannot find module')
expect(result.value).toBe('config-dir')
})
it('should resolve relative imports from the config directory when cwd is elsewhere', () => {
// cwd has no ./lib/origin, so resolving against cwd throws MODULE_NOT_FOUND
const result = loadConfigFrom(resolveData)
expect(result.stderr).not.toContain('Cannot find module')
expect(result.value).toBe('config-dir')
})
it('should not resolve relative imports from cwd when cwd has a matching file', () => {
// cwd has its own ./lib/origin, which must not be loaded instead
const result = loadConfigFrom(
join(resolveData, 'typescript-config-relative-import-cwd')
)
expect(result.stderr).not.toContain('Cannot find module')
expect(result.value).toBe('config-dir')
})
})
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment