Skip to content

Commit

Permalink
feat: virtual module for dynamicImportHelper
Browse files Browse the repository at this point in the history
  • Loading branch information
poyoho committed Apr 21, 2022
1 parent b505f42 commit 1bf029e
Show file tree
Hide file tree
Showing 4 changed files with 86 additions and 56 deletions.
4 changes: 2 additions & 2 deletions packages/vite/src/node/build.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ import { copyDir, emptyDir, lookupFile, normalizePath } from './utils'
import { manifestPlugin } from './plugins/manifest'
import commonjsPlugin from '@rollup/plugin-commonjs'
import type { RollupCommonJSOptions } from 'types/commonjs'
import { dynamicImportVars } from './plugins/dynamicImportVars'
import { dynamicImportVarsPlugin } from './plugins/dynamicImportVars'
import type { RollupDynamicImportVarsOptions } from 'types/dynamicImportVars'
import type { Logger } from './logger'
import type { TransformOptions } from 'esbuild'
Expand Down Expand Up @@ -313,7 +313,7 @@ export function resolveBuildPlugins(config: ResolvedConfig): {
watchPackageDataPlugin(config),
commonjsPlugin(options.commonjsOptions),
dataURIPlugin(),
dynamicImportVars(config),
dynamicImportVarsPlugin(config),
assetImportMetaUrlPlugin(config),
...(options.rollupOptions.plugins
? (options.rollupOptions.plugins.filter(Boolean) as Plugin[])
Expand Down
56 changes: 40 additions & 16 deletions packages/vite/src/node/plugins/dynamicImportVars.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,37 @@ import type { ResolvedConfig } from '../config'
import { transformDynamicImportGlob } from '../importGlob'
import { createFilter } from '@rollup/pluginutils'

export function dynamicImportVars(config: ResolvedConfig): Plugin {
const dynamicImportHelper = (glob: Record<string, any>, path: string) => {
const v = glob[path]
if (v) {
return typeof v === 'function' ? v() : Promise.resolve(v)
}
return new Promise((_, reject) => {
;(typeof queueMicrotask === 'function' ? queueMicrotask : setTimeout)(
reject.bind(null, new Error('Unknown variable dynamic import: ' + path))
)
})
}
export const dynamicImportHelperId = '/@vite/dynamic-import-helper'

export function dynamicImportHelperPlugin(): Plugin {
return {
name: 'vite:dynamic-import-helper',
resolveId(id) {
if (id === dynamicImportHelperId) {
return id
}
},

load(id) {
if (id === dynamicImportHelperId) {
return 'export default' + dynamicImportHelper.toString()
}
}
}
}

export function dynamicImportVarsPlugin(config: ResolvedConfig): Plugin {
const resolve = config.createResolver({
preferRelative: true,
tryIndex: false,
Expand Down Expand Up @@ -38,7 +68,8 @@ export function dynamicImportVars(config: ResolvedConfig): Plugin {
}

let s: MagicString | undefined
let importIndex = 0
let needDynamicImportHelper = false

for (let index = 0; index < imports.length; index++) {
const {
s: start,
Expand Down Expand Up @@ -80,27 +111,20 @@ export function dynamicImportVars(config: ResolvedConfig): Plugin {

const { rawPattern, exp } = result

s.prepend(`function __variableDynamicImportRuntime_${importIndex}_(path) {
const glob = ${exp}
const v = glob[path]
if (v) {
return typeof v === 'function' ? v() : Promise.resolve(v)
}
return new Promise((resolve, reject) => {
(typeof queueMicrotask === 'function' ? queueMicrotask : setTimeout)(
reject.bind(null, new Error("Unknown variable dynamic import: " + path))
);
})
}\n`)
needDynamicImportHelper = true
s.overwrite(
expStart,
expEnd,
`__variableDynamicImportRuntime_${importIndex}_(\`${rawPattern}\`)`
`__variableDynamicImportRuntimeHelper(${exp}, \`${rawPattern}\`)`
)
importIndex++
}

if (s) {
if (needDynamicImportHelper) {
s.prepend(
`import __variableDynamicImportRuntimeHelper from "${dynamicImportHelperId}";`
)
}
return {
code: s.toString(),
map: config.build.sourcemap ? s.generateMap({ hires: true }) : null
Expand Down
80 changes: 42 additions & 38 deletions packages/vite/src/node/plugins/importAnalysis.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ import {
getDepsCacheDir,
optimizedDepNeedsInterop
} from '../optimizer'
import { dynamicImportHelperId } from './dynamicImportVars'

const isDebug = !!process.env.DEBUG
const debug = createDebugger('vite:import-analysis')
Expand Down Expand Up @@ -183,6 +184,7 @@ export function importAnalysisPlugin(config: ResolvedConfig): Plugin {
let isSelfAccepting = false
let hasEnv = false
let needQueryInjectHelper = false
let needDynamicImportHelper = false
let s: MagicString | undefined
const str = () => s || (s = new MagicString(source))
const importedUrls = new Set<string>()
Expand Down Expand Up @@ -533,37 +535,31 @@ export function importAnalysisPlugin(config: ResolvedConfig): Plugin {
const url = rawUrl
.replace(/\/\*[\s\S]*?\*\/|([^\\:]|^)\/\/.*$/gm, '')
.trim()
if (!hasViteIgnore && !isSupportedDynamicImport(url)) {
const glob = await transformDynamicImportGlob(
source,
expStart,
expEnd,
importer,
start,
end,
config.root,
undefined,
resolve
)
if (!isSupportedDynamicImport(url)) {
let glob
try {
glob = await transformDynamicImportGlob(
source,
expStart,
expEnd,
importer,
start,
end,
config.root,
undefined,
resolve
)
} catch (e) {
this.error(e)
}

if (glob) {
const { exp, imports, rawPattern } = glob
str()
.prepend(`function __variableDynamicImportRuntime_${index}_(path) {
const glob = ${exp}
const v = glob[path]
if (v) {
return typeof v === 'function' ? v() : Promise.resolve(v)
}
return new Promise((resolve, reject) => {
(typeof queueMicrotask === 'function' ? queueMicrotask : setTimeout)(
reject.bind(null, new Error("Unknown variable dynamic import: " + path))
);
})
}\n`)
needDynamicImportHelper = true
str().overwrite(
expStart,
expEnd,
`__variableDynamicImportRuntime_${index}_(\`${rawPattern}\`)`
`__variableDynamicImportRuntimeHelper(${exp}, \`${rawPattern}\`)`
)
imports.forEach((url) => {
url = url.replace(base, '/')
Expand All @@ -580,19 +576,21 @@ export function importAnalysisPlugin(config: ResolvedConfig): Plugin {
pattern: rawPattern
})
} else {
this.warn(
`\n` +
colors.cyan(importerModule.file) +
if (!hasViteIgnore) {
this.warn(
`\n` +
generateCodeFrame(source, start) +
`\nThe above dynamic import cannot be analyzed by vite.\n` +
`See ${colors.blue(
`https://github.com/rollup/plugins/tree/master/packages/dynamic-import-vars#limitations`
)} ` +
`for supported dynamic import formats. ` +
`If this is intended to be left as-is, you can use the ` +
`/* @vite-ignore */ comment inside the import() call to suppress this warning.\n`
)
colors.cyan(importerModule.file) +
`\n` +
generateCodeFrame(source, start) +
`\nThe above dynamic import cannot be analyzed by vite.\n` +
`See ${colors.blue(
`https://github.com/rollup/plugins/tree/master/packages/dynamic-import-vars#limitations`
)} ` +
`for supported dynamic import formats. ` +
`If this is intended to be left as-is, you can use the ` +
`/* @vite-ignore */ comment inside the import() call to suppress this warning.\n`
)
}
}
}
if (
Expand Down Expand Up @@ -653,6 +651,12 @@ export function importAnalysisPlugin(config: ResolvedConfig): Plugin {
)
}

if (needDynamicImportHelper) {
str().prepend(
`import __variableDynamicImportRuntimeHelper from "${dynamicImportHelperId}";`
)
}

// normalize and rewrite accepted urls
const normalizedAcceptedUrls = new Set<string>()
for (const { url, start, end } of acceptedUrls) {
Expand Down
2 changes: 2 additions & 0 deletions packages/vite/src/node/plugins/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import { ssrRequireHookPlugin } from './ssrRequireHook'
import { workerImportMetaUrlPlugin } from './workerImportMetaUrl'
import { ensureWatchPlugin } from './ensureWatch'
import { metadataPlugin } from './metadata'
import { dynamicImportHelperPlugin } from './dynamicImportVars'

export async function resolvePlugins(
config: ResolvedConfig,
Expand Down Expand Up @@ -51,6 +52,7 @@ export async function resolvePlugins(
ssrConfig: config.ssr,
asSrc: true
}),
dynamicImportHelperPlugin(),
isBuild ? null : optimizedDepsPlugin(),
htmlInlineProxyPlugin(config),
cssPlugin(config),
Expand Down

0 comments on commit 1bf029e

Please sign in to comment.