MCPcopy
hub / github.com/vitejs/vite / transformDynamicImport

Function transformDynamicImport

packages/vite/src/node/plugins/dynamicImportVars.ts:114–167  ·  packages/vite/src/node/plugins/dynamicImportVars.ts::transformDynamicImport
(
  importSource: string,
  importer: string,
  resolve: (
    url: string,
    importer?: string,
  ) => Promise<string | undefined> | string | undefined,
  root: string,
)

Source from the content-addressed store, hash-verified

112}
113
114export async function transformDynamicImport(
115 importSource: string,
116 importer: string,
117 resolve: (
118 url: string,
119 importer?: string,
120 ) => Promise<string | undefined> | string | undefined,
121 root: string,
122): Promise<{
123 glob: string
124 pattern: string
125 rawPattern: string
126} | null> {
127 if (importSource[1] !== class="st">'.' && importSource[1] !== class="st">'/') {
128 const resolvedFileName = await resolve(importSource.slice(1, -1), importer)
129 if (!resolvedFileName) {
130 return null
131 }
132 const relativeFileName = normalizePath(
133 posix.relative(
134 posix.dirname(normalizePath(importer)),
135 normalizePath(resolvedFileName),
136 ),
137 )
138 importSource =
139 class="st">'`' + (relativeFileName[0] === class="st">'.' ? class="st">'' : class="st">'./') + relativeFileName + class="st">'`'
140 }
141
142 const dynamicImportPattern = parseDynamicImportPattern(importSource)
143 if (!dynamicImportPattern) {
144 return null
145 }
146 const { globParams, rawPattern, userPattern } = dynamicImportPattern
147 const params = globParams ? `, ${JSON.stringify(globParams)}` : class="st">''
148 const dir = importer ? posix.dirname(importer) : root
149 const normalized =
150 rawPattern[0] === class="st">'/'
151 ? posix.join(root, rawPattern.slice(1))
152 : posix.join(dir, rawPattern)
153
154 let newRawPattern = posix.relative(posix.dirname(importer), normalized)
155
156 if (!relativePathRE.test(newRawPattern)) {
157 newRawPattern = `./${newRawPattern}`
158 }
159
160 const exp = `(import.meta.glob(${JSON.stringify(userPattern)}${params}))`
161
162 return {
163 rawPattern: newRawPattern,
164 pattern: userPattern,
165 glob: exp,
166 }
167}
168
169export function dynamicImportVarsPlugin(config: ResolvedConfig): Plugin {
170 const resolve = createBackCompatIdResolver(config, {

Callers 2

runFunction · 0.90
handlerFunction · 0.85

Calls 3

normalizePathFunction · 0.90
resolveFunction · 0.70

Tested by 1

runFunction · 0.72