Skip to content

Commit

Permalink
fix: dynamic import path contain ../ and its own directory (#9350)
Browse files Browse the repository at this point in the history
  • Loading branch information
Dunqing committed Aug 16, 2022
1 parent 1d8613f commit c6870f3
Show file tree
Hide file tree
Showing 8 changed files with 71 additions and 5 deletions.
Expand Up @@ -8,6 +8,10 @@ exports[`parse positives > alias path 1`] = `"__variableDynamicImportRuntimeHelp
exports[`parse positives > basic 1`] = `"__variableDynamicImportRuntimeHelper((import.meta.glob(\\"./mods/*.js\\")), \`./mods/\${base}.js\`)"`;
exports[`parse positives > with ../ and itself 1`] = `"__variableDynamicImportRuntimeHelper((import.meta.glob(\\"../dynamicImportVar/*.js\\")), \`./\${name}.js\`)"`;
exports[`parse positives > with multi ../ and itself 1`] = `"__variableDynamicImportRuntimeHelper((import.meta.glob(\\"../../plugins/dynamicImportVar/*.js\\")), \`./\${name}.js\`)"`;
exports[`parse positives > with query raw 1`] = `"__variableDynamicImportRuntimeHelper((import.meta.glob(\\"./mods/*.js\\", {\\"as\\":\\"raw\\",\\"import\\":\\"*\\"})), \`./mods/\${base}.js\`)"`;
exports[`parse positives > with query url 1`] = `"__variableDynamicImportRuntimeHelper((import.meta.glob(\\"./mods/*.js\\")), \`./mods/\${base}.js\`)"`;
@@ -1,14 +1,18 @@
import { resolve } from 'node:path'
import { fileURLToPath } from 'node:url'
import { normalizePath } from 'vite'
import { describe, expect, it } from 'vitest'
import { transformDynamicImport } from '../../../plugins/dynamicImportVars'

const __dirname = resolve(fileURLToPath(import.meta.url), '..')

async function run(input: string) {
const { glob, rawPattern } =
(await transformDynamicImport(input, resolve(__dirname, 'index.js'), (id) =>
id.replace('@', resolve(__dirname, './mods/'))
(await transformDynamicImport(
input,
normalizePath(resolve(__dirname, 'index.js')),
(id) => id.replace('@', resolve(__dirname, './mods/')),
__dirname
)) || {}
return `__variableDynamicImportRuntimeHelper(${glob}, \`${rawPattern}\`)`
}
Expand Down Expand Up @@ -37,4 +41,14 @@ describe('parse positives', () => {
it('? in url', async () => {
expect(await run('`./mo?ds/${base ?? foo}.js?raw`')).toMatchSnapshot()
})

it('with ../ and itself', async () => {
expect(await run('`../dynamicImportVar/${name}.js`')).toMatchSnapshot()
})

it('with multi ../ and itself', async () => {
expect(
await run('`../../plugins/dynamicImportVar/${name}.js`')
).toMatchSnapshot()
})
})
23 changes: 20 additions & 3 deletions packages/vite/src/node/plugins/dynamicImportVars.ts
Expand Up @@ -14,6 +14,7 @@ import {
requestQuerySplitRE,
transformStableResult
} from '../utils'
import { toAbsoluteGlob } from './importMetaGlob'

export const dynamicImportHelperId = '/@vite/dynamic-import-helper'

Expand Down Expand Up @@ -77,7 +78,8 @@ export async function transformDynamicImport(
resolve: (
url: string,
importer?: string
) => Promise<string | undefined> | string | undefined
) => Promise<string | undefined> | string | undefined,
root: string
): Promise<{
glob: string
pattern: string
Expand Down Expand Up @@ -105,10 +107,20 @@ export async function transformDynamicImport(
const params = globParams
? `, ${JSON.stringify({ ...globParams, import: '*' })}`
: ''

let newRawPattern = posix.relative(
posix.dirname(importer),
await toAbsoluteGlob(rawPattern, root, importer, resolve)
)

if (!/^\.{1,2}\//.test(newRawPattern)) {
newRawPattern = `./${newRawPattern}`
}

const exp = `(import.meta.glob(${JSON.stringify(userPattern)}${params}))`

return {
rawPattern,
rawPattern: newRawPattern,
pattern: userPattern,
glob: exp
}
Expand Down Expand Up @@ -183,7 +195,12 @@ export function dynamicImportVarsPlugin(config: ResolvedConfig): Plugin {
// parenthesis, so we manually remove them for now.
// See https://github.com/guybedford/es-module-lexer/issues/118
const importSource = removeComments(source.slice(start, end)).trim()
result = await transformDynamicImport(importSource, importer, resolve)
result = await transformDynamicImport(
importSource,
importer,
resolve,
config.root
)
} catch (error) {
if (warnOnError) {
this.warn(error)
Expand Down
16 changes: 16 additions & 0 deletions playground/dynamic-import/__tests__/dynamic-import.spec.ts
Expand Up @@ -97,3 +97,19 @@ test('should load dynamic import with css in package', async () => {
await page.click('.pkg-css')
await untilUpdated(() => getColor('.pkg-css'), 'blue', true)
})

test('should work with load ../ and itself directory', async () => {
await untilUpdated(
() => page.textContent('.dynamic-import-self'),
'dynamic-import-self-content',
true
)
})

test('should work with load ../ and contain itself directory', async () => {
await untilUpdated(
() => page.textContent('.dynamic-import-nested-self'),
'dynamic-import-nested-self-content',
true
)
})
4 changes: 4 additions & 0 deletions playground/dynamic-import/index.html
Expand Up @@ -21,6 +21,10 @@

<div class="view"></div>

<div class="dynamic-import-self"></div>

<div class="dynamic-import-nested-self"></div>

<script type="module" src="./nested/index.js"></script>
<style>
p {
Expand Down
9 changes: 9 additions & 0 deletions playground/dynamic-import/nested/index.js
Expand Up @@ -102,4 +102,13 @@ import(`@/${base}.js`).then((mod) => {
text('.dynamic-import-with-vars-alias', mod.hi())
})

base = 'self'
import(`../nested/${base}.js`).then((mod) => {
text('.dynamic-import-self', mod.self)
})

import(`../nested/nested/${base}.js`).then((mod) => {
text('.dynamic-import-nested-self', mod.self)
})

console.log('index.js')
1 change: 1 addition & 0 deletions playground/dynamic-import/nested/nested/self.js
@@ -0,0 +1 @@
export const self = 'dynamic-import-nested-self-content'
1 change: 1 addition & 0 deletions playground/dynamic-import/nested/self.js
@@ -0,0 +1 @@
export const self = 'dynamic-import-self-content'

0 comments on commit c6870f3

Please sign in to comment.