Skip to content

Commit

Permalink
fix(glob): handle glob prop access (#9281)
Browse files Browse the repository at this point in the history
  • Loading branch information
bluwy committed Jul 21, 2022
1 parent bbc8318 commit 0580215
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 1 deletion.
7 changes: 6 additions & 1 deletion packages/vite/src/node/plugins/importMetaGlob.ts
Expand Up @@ -5,6 +5,7 @@ import type {
ArrayExpression,
CallExpression,
Literal,
MemberExpression,
Node,
SequenceExpression
} from 'estree'
Expand Down Expand Up @@ -118,7 +119,7 @@ export async function parseImportGlob(
return e
}

let ast: CallExpression | SequenceExpression
let ast: CallExpression | SequenceExpression | MemberExpression
let lastTokenPos: number | undefined

try {
Expand Down Expand Up @@ -157,6 +158,10 @@ export async function parseImportGlob(
if (ast.type === 'SequenceExpression')
ast = ast.expressions[0] as CallExpression

// immediate property access, call expression is nested
// import.meta.glob(...)['prop']
if (ast.type === 'MemberExpression') ast = ast.object as CallExpression

if (ast.type !== 'CallExpression')
throw err(`Expect CallExpression, got ${ast.type}`)

Expand Down
6 changes: 6 additions & 0 deletions playground/glob-import/__tests__/glob-import.spec.ts
Expand Up @@ -92,6 +92,12 @@ test('import glob raw', async () => {
)
})

test('import property access', async () => {
expect(await page.textContent('.property-access')).toBe(
JSON.stringify(rawResult['/dir/baz.json'], null, 2)
)
})

test('import relative glob raw', async () => {
expect(await page.textContent('.relative-glob-raw')).toBe(
JSON.stringify(relativeRawResult, null, 2)
Expand Down
21 changes: 21 additions & 0 deletions playground/glob-import/index.html
@@ -1,8 +1,17 @@
<h1>Glob import</h1>
<h2>Normal</h2>
<pre class="result"></pre>
<h2>Eager</h2>
<pre class="result-eager"></pre>
<h2>node_modules</h2>
<pre class="result-node_modules"></pre>
<h2>Raw</h2>
<pre class="globraw"></pre>
<h2>Property access</h2>
<pre class="property-access"></pre>
<h2>Relative raw</h2>
<pre class="relative-glob-raw"></pre>
<h2>Side effect</h2>
<pre class="side-effect-result"></pre>

<script type="module" src="./dir/index.js"></script>
Expand Down Expand Up @@ -63,6 +72,18 @@
)
</script>

<script type="module">
const bazJson = import.meta.glob('/dir/*.json', {
as: 'raw',
eager: true
})['/dir/baz.json']
document.querySelector('.property-access').textContent = JSON.stringify(
JSON.parse(bazJson),
null,
2
)
</script>

<script type="module">
const relativeRawModules = import.meta.glob('../glob-import/dir/*.json', {
as: 'raw',
Expand Down

0 comments on commit 0580215

Please sign in to comment.