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: import.meta.glob support ?raw #5545

Merged
merged 7 commits into from
Dec 28, 2021
Merged
Show file tree
Hide file tree
Changes from 5 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
12 changes: 12 additions & 0 deletions packages/playground/glob-import/__tests__/glob-import.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,12 +45,24 @@ const allResult = {
}
}

const rawResult = {
'/dir/baz.json': {
msg: 'baz'
}
}

test('should work', async () => {
expect(await page.textContent('.result')).toBe(
JSON.stringify(allResult, null, 2)
)
})

test('import glob raw', async () => {
expect(await page.textContent('.globraw')).toBe(
JSON.stringify(rawResult, null, 2)
)
})

if (!isBuild) {
test('hmr for adding/removing files', async () => {
addFile('dir/a.js', '')
Expand Down
16 changes: 16 additions & 0 deletions packages/playground/glob-import/index.html
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
<pre class="result"></pre>
<pre class="globraw"></pre>

<script type="module" src="./dir/index.js"></script>
<script type="module">
Expand All @@ -19,3 +20,18 @@
document.querySelector('.result').textContent = JSON.stringify(res, null, 2)
})
</script>

<script type="module">
const rawModules = import.meta.globEager('/dir/*.json', {
assert: { type: 'raw' }
})
const globraw = {}
Object.keys(rawModules).forEach((key) => {
globraw[key] = JSON.parse(rawModules[key])
})
document.querySelector('.globraw').textContent = JSON.stringify(
globraw,
null,
2
)
</script>
1 change: 0 additions & 1 deletion packages/playground/ssr-vue/__tests__/ssr-vue.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@ test('vuex can be import succeed by named import', async () => {
expect(storeHtml).toMatch('bar')
})


test('/about', async () => {
await page.goto(url + '/about')
expect(await page.textContent('h1')).toMatch('About')
Expand Down
1 change: 1 addition & 0 deletions packages/vite/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@
"//": "READ CONTRIBUTING.md to understand what to put under deps vs. devDeps!",
"dependencies": {
"esbuild": "^0.13.12",
"json5": "^2.2.0",
"postcss": "^8.3.11",
"resolve": "^1.20.0",
"rollup": "^2.59.0"
Expand Down
32 changes: 27 additions & 5 deletions packages/vite/src/node/importGlob.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import path from 'path'
import { promises as fsp } from 'fs'
import glob from 'fast-glob'
import * as JSON5 from 'json5'
import {
isModernFlag,
preloadMethod,
Expand All @@ -8,6 +10,12 @@ import {
import { cleanUrl } from './utils'
import { RollupError } from 'rollup'

export interface AssertOptions {
assert?: {
type: string
}
}

export async function transformImportGlob(
source: string,
pos: number,
Expand Down Expand Up @@ -38,7 +46,7 @@ export async function transformImportGlob(
importer = cleanUrl(importer)
const importerBasename = path.basename(importer)

let [pattern, endIndex] = lexGlobPattern(source, pos)
let [pattern, assertion, endIndex] = lexGlobPattern(source, pos)
if (!pattern.startsWith('.') && !pattern.startsWith('/')) {
throw err(`pattern must start with "." or "/" (relative to project root)`)
}
Expand Down Expand Up @@ -79,8 +87,12 @@ export async function transformImportGlob(
;[importee] = await normalizeUrl(file, pos)
}
imports.push(importee)
const identifier = `__glob_${importIndex}_${i}`
if (isEager) {
if (assertion?.assert?.type === 'raw') {
entries += ` ${JSON.stringify(file)}: ${JSON.stringify(
await fsp.readFile(path.join(base, file), 'utf-8')
)},`
patak-dev marked this conversation as resolved.
Show resolved Hide resolved
} else if (isEager) {
const identifier = `__glob_${importIndex}_${i}`
importsString += `import ${
isEagerDefault ? `` : `* as `
}${identifier} from ${JSON.stringify(importee)};`
Expand Down Expand Up @@ -115,7 +127,10 @@ const enum LexerState {
inTemplateString
}

function lexGlobPattern(code: string, pos: number): [string, number] {
function lexGlobPattern(
code: string,
pos: number
): [string, AssertOptions, number] {
let state = LexerState.inCall
let pattern = ''

Expand Down Expand Up @@ -161,7 +176,14 @@ 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 = code.indexOf(`)`, i)
const options = code.substring(i + 1, endIndex)
const commaIndex = options.indexOf(`,`)
let assert = {}
if (commaIndex > -1) {
assert = JSON5.parse(options.substr(commaIndex + 1))
Copy link
Member

Choose a reason for hiding this comment

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

Suggested change
assert = JSON5.parse(options.substr(commaIndex + 1))
assert = JSON5.parse(options.substring(commaIndex + 1))

There was a recent PR that converted substr to substring. I think we can do the same here too.

}
return [pattern, assert, endIndex + 1]
}

function error(pos: number) {
Expand Down
2 changes: 2 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.