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

fix: transform import.meta.glob when scan JS/TS #10634 #10635

Merged
merged 2 commits into from
Nov 1, 2022
Merged
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
51 changes: 32 additions & 19 deletions packages/vite/src/node/optimizer/scan.ts
Original file line number Diff line number Diff line change
Expand Up @@ -200,6 +200,29 @@ function esbuildScanPlugin(
external: !entries.includes(path)
})

const doTransformGlobImport = async (
contents: string,
id: string,
loader: Loader
) => {
let transpiledContents
// transpile because `transformGlobImport` only expects js
if (loader !== 'js') {
transpiledContents = (await transform(contents, { loader })).code
} else {
transpiledContents = contents
}

const result = await transformGlobImport(
transpiledContents,
id,
config.root,
resolve
)

return result?.s.toString() || transpiledContents
}

return {
name: 'vite:dep-scan',
setup(build) {
Expand Down Expand Up @@ -305,26 +328,9 @@ function esbuildScanPlugin(

const key = `${path}?id=${scriptId++}`
if (contents.includes('import.meta.glob')) {
let transpiledContents
// transpile because `transformGlobImport` only expects js
if (loader !== 'js') {
transpiledContents = (await transform(contents, { loader }))
.code
} else {
transpiledContents = contents
}

scripts[key] = {
loader: 'js', // since it is transpiled
contents:
(
await transformGlobImport(
transpiledContents,
path,
config.root,
resolve
)
)?.s.toString() || transpiledContents,
contents: await doTransformGlobImport(contents, path, loader),
pluginData: {
htmlType: { loader }
}
Expand Down Expand Up @@ -481,7 +487,7 @@ function esbuildScanPlugin(
// for jsx/tsx, we need to access the content and check for
// presence of import.meta.glob, since it results in import relationships
// but isn't crawled by esbuild.
build.onLoad({ filter: JS_TYPES_RE }, ({ path: id }) => {
build.onLoad({ filter: JS_TYPES_RE }, async ({ path: id }) => {
let ext = path.extname(id).slice(1)
if (ext === 'mjs') ext = 'js'

Expand All @@ -494,6 +500,13 @@ function esbuildScanPlugin(
config.optimizeDeps?.esbuildOptions?.loader?.[`.${ext}`] ||
(ext as Loader)

if (contents.includes('import.meta.glob')) {
candy-Tong marked this conversation as resolved.
Show resolved Hide resolved
return {
loader: 'js', // since it is transpiled,
contents: await doTransformGlobImport(contents, id, loader)
}
}

return {
loader,
contents
Expand Down