Skip to content

Commit

Permalink
fix(vite-node): normalize relative paths to be from current working d…
Browse files Browse the repository at this point in the history
…irectory (#952)
  • Loading branch information
kalvenschraut committed Mar 16, 2022
1 parent 21dace7 commit 7b98344
Show file tree
Hide file tree
Showing 4 changed files with 15 additions and 0 deletions.
1 change: 1 addition & 0 deletions packages/vite-node/src/client.ts
Expand Up @@ -59,6 +59,7 @@ export class ViteNodeRunner {
const resolvedDep = await this.options.resolveId(dep, id)
dep = resolvedDep?.id?.replace(this.root, '') || dep
}

if (callstack.includes(dep)) {
if (!this.moduleCache.get(dep)?.exports)
throw new Error(`[vite-node] Circular dependency detected\nStack:\n${[...callstack, dep].reverse().map(p => `- ${p}`).join('\n')}`)
Expand Down
3 changes: 3 additions & 0 deletions packages/vite-node/src/server.ts
@@ -1,3 +1,4 @@
import { join } from 'pathe'
import type { TransformResult, ViteDevServer } from 'vite'
import type { FetchResult, RawSourceMap, ViteNodeResolveId, ViteNodeServerOptions } from './types'
import { shouldExternalize } from './externalize'
Expand All @@ -24,6 +25,8 @@ export class ViteNodeServer {
}

async resolveId(id: string, importer?: string): Promise<ViteNodeResolveId | null> {
if (importer && !importer.startsWith(this.server.config.root))
importer = join(this.server.config.root, importer)
return this.server.pluginContainer.resolveId(id, importer, { ssr: true })
}

Expand Down
3 changes: 3 additions & 0 deletions test/core/src/relative-import.ts
@@ -0,0 +1,3 @@
export function dynamicRelativeImport(file: string) {
return import(`./${file}.ts`)
}
8 changes: 8 additions & 0 deletions test/core/test/imports.test.ts
@@ -1,4 +1,5 @@
import { expect, test } from 'vitest'
import { dynamicRelativeImport } from '../src/relative-import'

test('dynamic relative import works', async() => {
const stringTimeoutMod = await import('./../src/timeout')
Expand All @@ -9,6 +10,13 @@ test('dynamic relative import works', async() => {
expect(stringTimeoutMod).toBe(variableTimeoutMod)
})

test('Relative imports in imported modules work', async() => {
const relativeImportFromFile = await dynamicRelativeImport('timeout')
const directImport = await import('./../src/timeout')

expect(relativeImportFromFile).toBe(directImport)
})

test('dynamic aliased import works', async() => {
const stringTimeoutMod = await import('./../src/timeout')

Expand Down

0 comments on commit 7b98344

Please sign in to comment.