Skip to content

Commit

Permalink
fix(lexGlobPattern): edge case of glob import (#6022)
Browse files Browse the repository at this point in the history
  • Loading branch information
ygj6 authored Dec 10, 2021
1 parent e1d82fc commit d4c5cff
Show file tree
Hide file tree
Showing 3 changed files with 41 additions and 2 deletions.
1 change: 1 addition & 0 deletions docs/guide/features.md
Original file line number Diff line number Diff line change
Expand Up @@ -296,6 +296,7 @@ Note that:
- The glob patterns are treated like import specifiers: they must be either relative (start with `./`) or absolute (start with `/`, resolved relative to project root).
- The glob matching is done via `fast-glob` - check out its documentation for [supported glob patterns](https://github.com/mrmlnc/fast-glob#pattern-syntax).
- You should also be aware that glob imports do not accept variables, you need to directly pass the string pattern.
- The glob patterns cannot contain the same quote string (i.e. `'`, `"`, `` ` ``) as outer quotes, e.g. `'/Tom\'s files/**'`, use `"/Tom's files/**"` instead.

## WebAssembly

Expand Down
8 changes: 7 additions & 1 deletion packages/playground/glob-import/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,13 @@

<script type="module" src="./dir/index.js"></script>
<script type="module">
const modules = import.meta.glob('/dir/**')
const modules = import.meta.glob(
'/dir/**'
// for test: annotation contain ")"
/*
* for test: annotation contain ")"
* */
)

for (const path in modules) {
modules[path]().then((mod) => {
Expand Down
34 changes: 33 additions & 1 deletion packages/vite/src/node/importGlob.ts
Original file line number Diff line number Diff line change
Expand Up @@ -161,7 +161,39 @@ function lexGlobPattern(code: string, pos: number): [string, number] {
throw new Error('unknown import.meta.glob lexer state')
}
}
return [pattern, code.indexOf(`)`, i) + 1]

const endIndex = getEndIndex(code, i)
return [pattern, endIndex + 1]
}

// reg without the 'g' option, only matches the first match
const multilineCommentsRE = /\/\*(.|[\r\n])*?\*\//m
const singlelineCommentsRE = /\/\/.*/

function getEndIndex(code: string, i: number): number {
const findStart = i
const endIndex = code.indexOf(`)`, findStart)
const subCode = code.substring(findStart)

const matched =
subCode.match(singlelineCommentsRE) ?? subCode.match(multilineCommentsRE)
if (!matched) {
return endIndex
}

const str = matched[0]
const index = matched.index
if (!index) {
return endIndex
}

const commentStart = findStart + index
const commentEnd = commentStart + str.length
if (endIndex > commentStart && endIndex < commentEnd) {
return getEndIndex(code, commentEnd)
} else {
return endIndex
}
}

function error(pos: number) {
Expand Down

0 comments on commit d4c5cff

Please sign in to comment.