Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: dynamic import path contain ../ and its own directory #9350

Merged
merged 7 commits into from Aug 16, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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 } =
poyoho marked this conversation as resolved.
Show resolved Hide resolved
(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}`
}
Comment on lines +111 to +118
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't understand this logic, do we have enough tests for all cases here?
If importer is /root/dir/nested/importer.js and toAbsoluteGlob returns /root/foo/bar/{pattern}.js, then newRawPattern ends up being ./../foo/bar/{pattern}.js 🤔

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ah, no.. I missed the !. Ok, now I understand 😄


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 @@ -96,3 +96,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'