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

feat: add base option for import.meta.glob #18510

Open
wants to merge 16 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ export const cleverCwd2 = /* #__PURE__ */ Object.assign({"./modules/a.ts": () =>


});
export const customBase = /* #__PURE__ */ Object.assign({"fixture-a/modules/a.ts": () => import("./modules/a.ts"),"fixture-a/modules/b.ts": () => import("./modules/b.ts"),"fixture-a/modules/index.ts": () => import("./modules/index.ts"),"fixture-a/sibling.ts": () => import("./sibling.ts")});
sapphi-red marked this conversation as resolved.
Show resolved Hide resolved
"
`;

Expand Down Expand Up @@ -107,6 +108,7 @@ export const cleverCwd2 = /* #__PURE__ */ Object.assign({"./modules/a.ts": () =>


});
export const customBase = /* #__PURE__ */ Object.assign({"fixture-a/modules/a.ts": () => import("./modules/a.ts"),"fixture-a/modules/b.ts": () => import("./modules/b.ts"),"fixture-a/modules/index.ts": () => import("./modules/index.ts"),"fixture-a/sibling.ts": () => import("./sibling.ts")});
"
`;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -67,3 +67,5 @@ export const cleverCwd2 = import.meta.glob([
'../fixture-b/*.ts',
'!**/index.ts',
])

export const customBase = import.meta.glob('**/*.ts', { base: './' })
sapphi-red marked this conversation as resolved.
Show resolved Hide resolved
35 changes: 35 additions & 0 deletions packages/vite/src/node/__tests__/plugins/importGlob/parse.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,28 @@ describe('parse positives', async () => {
`)
})

it('options with base', async () => {
expect(
await run(`
import.meta.glob('**/dir/*.md', {
base: './path/to/base'
})
`),
).toMatchInlineSnapshot(`
[
{
"globs": [
"**/dir/*.md",
],
"options": {
"base": "./path/to/base",
},
"start": 5,
},
]
`)
})

it('object properties - 1', async () => {
expect(
await run(`
Expand Down Expand Up @@ -376,4 +398,17 @@ describe('parse negatives', async () => {
'[Error: Vite is unable to parse the glob options as the value is not static]',
)
})

it('options base', async () => {
expect(
await runError('import.meta.glob("./*.js", { base: 1 })'),
).toMatchInlineSnapshot(
'[Error: Expected glob option "base" to be of type string, but got number]',
)
expect(
await runError('import.meta.glob("./*.js", { base: "foo" })'),
).toMatchInlineSnapshot(
'[Error: Invalid glob: "foo/*.js" (resolved: "foo/*.js"). It must start with \'/\' or \'./\']',
)
})
})
19 changes: 15 additions & 4 deletions packages/vite/src/node/plugins/importMetaGlob.ts
sapphi-red marked this conversation as resolved.
Show resolved Hide resolved
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,7 @@ const knownOptions = {
import: ['string'],
exhaustive: ['boolean'],
query: ['object', 'string'],
base: ['string'],
sapphi-red marked this conversation as resolved.
Show resolved Hide resolved
}

const forceDefaultAs = ['raw', 'url']
Expand Down Expand Up @@ -306,7 +307,9 @@ export async function parseImportGlob(
}

const globsResolved = await Promise.all(
globs.map((glob) => toAbsoluteGlob(glob, root, importer, resolveId)),
globs.map((glob) =>
toAbsoluteGlob(glob, root, importer, resolveId, options.base),
),
)
const isRelative = globs.every((i) => '.!'.includes(i[0]))

Expand Down Expand Up @@ -416,15 +419,20 @@ export async function transformGlobImport(
throw new Error(
"In virtual modules, all globs must start with '/'",
)
const filePath = `/${relative(root, file)}`
return { filePath, importPath: filePath }
const importPath = `/${relative(root, file)}`
const filePath = options.base
? `${relative(posix.join(root, options.base), file)}`
: importPath
return { filePath, importPath }
bluwy marked this conversation as resolved.
Show resolved Hide resolved
}

let importPath = relative(dir, file)
if (importPath[0] !== '.') importPath = `./${importPath}`

let filePath: string
if (isRelative) {
if (options.base) {
filePath = relative(posix.join(root, options.base), file)
} else if (isRelative) {
filePath = importPath
} else {
filePath = relative(root, file)
Expand Down Expand Up @@ -544,6 +552,7 @@ export async function toAbsoluteGlob(
root: string,
importer: string | undefined,
resolveId: IdResolver,
base?: string,
): Promise<string> {
let pre = ''
if (glob[0] === '!') {
Expand All @@ -552,6 +561,8 @@ export async function toAbsoluteGlob(
}
root = globSafePath(root)
const dir = importer ? globSafePath(dirname(importer)) : root
if (base && base.startsWith('./')) return pre + posix.join(dir, base, glob)
glob = base ? posix.join(base, glob) : glob
bluwy marked this conversation as resolved.
Show resolved Hide resolved
if (glob[0] === '/') return pre + posix.join(root, glob.slice(1))
if (glob.startsWith('./')) return pre + posix.join(dir, glob.slice(2))
if (glob.startsWith('../')) return pre + posix.join(dir, glob)
Expand Down
4 changes: 4 additions & 0 deletions packages/vite/types/importGlob.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,10 @@ export interface ImportGlobOptions<
* @default false
*/
exhaustive?: boolean
/**
* Base path to resolve relative paths.
*/
base?: string
}

export type GeneralImportGlobOptions = ImportGlobOptions<boolean, string>
Expand Down
12 changes: 12 additions & 0 deletions playground/glob-import/__tests__/glob-import.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,12 @@ const relativeRawResult = {
},
}

const baseRawResult = {
'baz.json': {
msg: 'baz',
},
}

test('should work', async () => {
await withRetry(async () => {
const actual = await page.textContent('.result')
Expand Down Expand Up @@ -247,3 +253,9 @@ test('subpath imports', async () => {
test('#alias imports', async () => {
expect(await page.textContent('.hash-alias-imports')).toMatch('bar foo')
})

test('import base glob raw', async () => {
expect(await page.textContent('.result-base')).toBe(
JSON.stringify(baseRawResult, null, 2),
)
})
20 changes: 20 additions & 0 deletions playground/glob-import/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,8 @@ <h2>#alias imports</h2>
<pre class="hash-alias-imports"></pre>
<h2>In package</h2>
<pre class="in-package"></pre>
<h2>Base</h2>
<pre class="result-base"></pre>

<script type="module" src="./dir/index.js"></script>
<script type="module">
Expand Down Expand Up @@ -167,3 +169,21 @@ <h2>In package</h2>
<script type="module">
import '@vitejs/test-import-meta-glob-pkg'
</script>

<script type="module">
const baseModules = import.meta.glob('*.json', {
query: '?raw',
eager: true,
import: 'default',
base: './dir',
})
const globBase = {}
Object.keys(baseModules).forEach((key) => {
globBase[key] = JSON.parse(baseModules[key])
})
document.querySelector('.result-base').textContent = JSON.stringify(
globBase,
null,
2,
)
</script>