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 (#17453) #17625

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all 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
28 changes: 24 additions & 4 deletions packages/vite/src/node/plugins/importMetaGlob.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ export interface ParsedImportGlob {

interface ParsedGeneralImportGlobOptions extends GeneralImportGlobOptions {
query?: string
base?: string
}

export function getAffectedGlobModules(
Expand Down Expand Up @@ -114,6 +115,7 @@ const knownOptions = {
import: ['string'],
exhaustive: ['boolean'],
query: ['object', 'string'],
base: ['string'],
}

const forceDefaultAs = ['raw', 'url']
Expand Down Expand Up @@ -303,7 +305,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 @@ -414,15 +418,26 @@ export async function transformGlobImport(
throw new Error(
"In virtual modules, all globs must start with '/'",
)
const filePath = `/${relative(root, file)}`
return { filePath, importPath: filePath }

if (options.base) {
const rootBase = posix.join(root, options.base)
const filePath = `${relative(rootBase, file)}`
const importPath = `/${relative(root, file)}`
return { filePath, importPath }
} else {
const filePath = `/${relative(root, file)}`
return { filePath, importPath: filePath }
}
}

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

let filePath: string
if (isRelative) {
if (options.base) {
const rootBase = posix.join(root, options.base)
filePath = relative(rootBase, file)
} else if (isRelative) {
filePath = importPath
} else {
filePath = relative(root, file)
Expand Down Expand Up @@ -543,6 +558,7 @@ export async function toAbsoluteGlob(
root: string,
importer: string | undefined,
resolveId: IdResolver,
base?: string,
): Promise<string> {
let pre = ''
if (glob[0] === '!') {
Expand All @@ -551,9 +567,13 @@ export async function toAbsoluteGlob(
}
root = globSafePath(root)
const dir = importer ? globSafePath(dirname(importer)) : root

glob = base ? posix.join(base, glob) : glob

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)
if (base && !posix.isAbsolute(base)) return pre + posix.join(dir, glob)
if (glob.startsWith('**')) return pre + glob

const isSubImportsPattern = glob[0] === '#' && glob.includes('*')
Expand Down
3 changes: 3 additions & 0 deletions playground/glob-import/dir/d/e/f.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"msg": "f"
}
3 changes: 3 additions & 0 deletions playground/glob-import/dir/d/e/g.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"msg": "g"
}
33 changes: 33 additions & 0 deletions playground/glob-import/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,8 @@ <h2>Sub imports</h2>
<pre class="sub-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 @@ -162,3 +164,34 @@ <h2>In package</h2>
<script type="module">
import '@vitejs/test-import-meta-glob-pkg'
</script>

<script type="module">
// const rawModules1 = import.meta.glob('**/*.json', {
// // query: '?raw',
// eager: true,
// import: 'default',
// base: '/dir/d',
// })
// const rawModules2 = import.meta.glob('**/*.json', {
// // query: '?raw',
// eager: true,
// import: 'default',
// base: '../glob-import/dir/d',
// })
const baseModules = import.meta.glob('**/*.json', {
query: '?raw',
eager: true,
import: 'default',
base: './dir/d',
})

const globbase = {}
Object.keys(baseModules).forEach((key) => {
globbase[key] = JSON.parse(baseModules[key])
})
document.querySelector('.result-base').textContent = JSON.stringify(
globbase,
null,
2,
)
</script>
Loading