From bda0dc50b446340f6e83e24c18c305c39e289aeb Mon Sep 17 00:00:00 2001 From: patak-dev Date: Mon, 29 Apr 2024 14:29:48 +0200 Subject: [PATCH] feat: this.environment in buildStart, rework more internal plugins --- packages/vite/src/node/build.ts | 13 ++- packages/vite/src/node/config.ts | 7 +- packages/vite/src/node/plugin.ts | 1 + packages/vite/src/node/plugins/asset.ts | 82 +++++++++-------- .../src/node/plugins/assetImportMetaUrl.ts | 4 +- packages/vite/src/node/plugins/css.ts | 32 +++---- packages/vite/src/node/plugins/html.ts | 6 +- .../src/node/plugins/importAnalysisBuild.ts | 89 +++++++++++-------- packages/vite/src/node/plugins/manifest.ts | 22 +++-- packages/vite/src/node/plugins/wasm.ts | 2 +- packages/vite/src/node/plugins/worker.ts | 7 +- .../src/node/plugins/workerImportMetaUrl.ts | 2 +- 12 files changed, 155 insertions(+), 112 deletions(-) diff --git a/packages/vite/src/node/build.ts b/packages/vite/src/node/build.ts index 135426c5791de5..43364268a9b2a8 100644 --- a/packages/vite/src/node/build.ts +++ b/packages/vite/src/node/build.ts @@ -496,7 +496,7 @@ export async function resolveBuildPlugins(config: ResolvedConfig): Promise<{ ...(options.minify ? [terserPlugin(config)] : []), ...(!config.isWorker ? [ - ...(options.manifest ? [manifestPlugin(config)] : []), + ...(options.manifest ? [manifestPlugin()] : []), ...(options.ssrManifest ? [ssrManifestPlugin(config)] : []), buildReporterPlugin(config), ] @@ -1083,12 +1083,20 @@ export function injectEnvironmentToHooks( plugin: Plugin, environment?: BuildEnvironment, ): Plugin { - const { resolveId, load, transform, generateBundle, renderChunk } = plugin + const { + buildStart, + resolveId, + load, + transform, + generateBundle, + renderChunk, + } = plugin return { ...plugin, resolveId: wrapEnvironmentResolveId(resolveId, environment), load: wrapEnvironmentLoad(load, environment), transform: wrapEnvironmentTransform(transform, environment), + buildStart: wrapEnvironmentHook(buildStart, environment), generateBundle: wrapEnvironmentHook(generateBundle, environment), renderChunk: wrapEnvironmentHook(renderChunk, environment), } @@ -1303,6 +1311,7 @@ export type RenderBuiltAssetUrl = ( }, ) => string | { relative?: boolean; runtime?: string } | undefined +// TODO: experimental.renderBuiltUrl => environment.build.renderBuiltUrl? export function toOutputFilePathInJS( filename: string, type: 'asset' | 'public', diff --git a/packages/vite/src/node/config.ts b/packages/vite/src/node/config.ts index f3a05f0862faa8..57ef0c356669f4 100644 --- a/packages/vite/src/node/config.ts +++ b/packages/vite/src/node/config.ts @@ -491,7 +491,9 @@ export interface LegacyOptions { export interface ResolvedWorkerOptions { format: 'es' | 'iife' - plugins: (bundleChain: string[]) => Promise + plugins: ( + bundleChain: string[], + ) => Promise<{ plugins: Plugin[]; config: ResolvedConfig }> rollupOptions: RollupOptions } @@ -1084,6 +1086,7 @@ export async function resolveConfig( ) } + // TODO: Workers as environments could allow us to remove a lot of complexity const createWorkerPlugins = async function (bundleChain: string[]) { // Some plugins that aren't intended to work in the bundling of workers (doing post-processing at build time for example). // And Plugins may also have cached that could be corrupted by being used in these extra rollup calls. @@ -1130,7 +1133,7 @@ export async function resolveConfig( .map((hook) => hook(workerResolved)), ) - return resolvedWorkerPlugins + return { plugins: resolvedWorkerPlugins, config: workerResolved } } const resolvedWorkerOptions: ResolvedWorkerOptions = { diff --git a/packages/vite/src/node/plugin.ts b/packages/vite/src/node/plugin.ts index 7c7104c9b21aad..98297653deb96d 100644 --- a/packages/vite/src/node/plugin.ts +++ b/packages/vite/src/node/plugin.ts @@ -183,6 +183,7 @@ export interface BasePlugin extends RollupPlugin { > // TODO: abstract to every hook in RollupPlugin? + buildStart?: ModifyHookContext['buildStart'], PluginContext> generateBundle?: ModifyHookContext< RollupPlugin['generateBundle'], PluginContext diff --git a/packages/vite/src/node/plugins/asset.ts b/packages/vite/src/node/plugins/asset.ts index 1a15022e03d423..36a6b510b66a51 100644 --- a/packages/vite/src/node/plugins/asset.ts +++ b/packages/vite/src/node/plugins/asset.ts @@ -3,18 +3,15 @@ import { parse as parseUrl } from 'node:url' import fsp from 'node:fs/promises' import { Buffer } from 'node:buffer' import * as mrmime from 'mrmime' -import type { - NormalizedOutputOptions, - PluginContext, - RenderedChunk, -} from 'rollup' +import type { NormalizedOutputOptions, RenderedChunk } from 'rollup' import MagicString from 'magic-string' import colors from 'picocolors' import { createToImportMetaURLBasedRelativeRuntime, toOutputFilePathInJS, } from '../build' -import type { Plugin } from '../plugin' +import type { Plugin, PluginContext } from '../plugin' +import type { Environment } from '../environment' import type { ResolvedConfig } from '../config' import { checkPublicFile } from '../publicDir' import { @@ -36,7 +33,7 @@ export const assetUrlRE = /__VITE_ASSET__([\w$]+)__(?:\$_(.*?)__)?/g const jsSourceMapRE = /\.[cm]?js\.map$/ -const assetCache = new WeakMap>() +const assetCache = new WeakMap>() // chunk.name is the basename for the asset ignoring the directory structure // For the manifest, we need to preserve the original file path and isEntry @@ -45,8 +42,8 @@ export interface GeneratedAssetMeta { originalName: string isEntry?: boolean } -export const generatedAssets = new WeakMap< - ResolvedConfig, +export const generatedAssetsMap = new WeakMap< + Environment, Map >() @@ -62,11 +59,13 @@ export function registerCustomMime(): void { export function renderAssetUrlInJS( ctx: PluginContext, - config: ResolvedConfig, chunk: RenderedChunk, opts: NormalizedOutputOptions, code: string, ): MagicString | undefined { + const environment = ctx.environment! + const { config } = environment + const toRelativeRuntime = createToImportMetaURLBasedRelativeRuntime( opts.format, config.isWorker, @@ -145,8 +144,12 @@ export function assetPlugin(config: ResolvedConfig): Plugin { name: 'vite:asset', buildStart() { - assetCache.set(config, new Map()) - generatedAssets.set(config, new Map()) + const { environment } = this + if (!environment) { + return + } + assetCache.set(environment, new Map()) + generatedAssetsMap.set(environment, new Map()) }, resolveId(id) { @@ -189,7 +192,7 @@ export function assetPlugin(config: ResolvedConfig): Plugin { } id = removeUrlQuery(id) - let url = await fileToUrl(id, config, this) + let url = await fileToUrl(this, id) // Inherit HMR timestamp if this asset was invalidated const environment = this.environment @@ -212,12 +215,12 @@ export function assetPlugin(config: ResolvedConfig): Plugin { }, renderChunk(code, chunk, opts) { - const s = renderAssetUrlInJS(this, config, chunk, opts, code) + const s = renderAssetUrlInJS(this, chunk, opts, code) if (s) { return { code: s.toString(), - map: config.build.sourcemap + map: this.environment?.options.build.sourcemap ? s.generateMap({ hires: 'boundary' }) : null, } @@ -227,6 +230,8 @@ export function assetPlugin(config: ResolvedConfig): Plugin { }, generateBundle(_, bundle) { + const environment = this.environment! + // Remove empty entry point file for (const file in bundle) { const chunk = bundle[file] @@ -241,11 +246,7 @@ export function assetPlugin(config: ResolvedConfig): Plugin { } // do not emit assets for SSR build - if ( - config.command === 'build' && - config.build.ssr && - !config.build.emitAssets - ) { + if (config.command === 'build' && !environment.options.build.emitAssets) { for (const file in bundle) { if ( bundle[file].type === 'asset' && @@ -261,14 +262,14 @@ export function assetPlugin(config: ResolvedConfig): Plugin { } export async function fileToUrl( - id: string, - config: ResolvedConfig, ctx: PluginContext, + id: string, ): Promise { - if (config.command === 'serve') { - return fileToDevUrl(id, config) + const environment = ctx.environment! + if (environment.config.command === 'serve') { + return fileToDevUrl(id, environment.config) } else { - return fileToBuiltUrl(id, config, ctx) + return fileToBuiltUrl(ctx, id) } } @@ -336,17 +337,18 @@ function isGitLfsPlaceholder(content: Buffer): boolean { * and returns the resolved public URL */ async function fileToBuiltUrl( - id: string, - config: ResolvedConfig, pluginContext: PluginContext, + id: string, skipPublicCheck = false, forceInline?: boolean, ): Promise { + const environment = pluginContext.environment! + const { config } = environment if (!skipPublicCheck && checkPublicFile(id, config)) { return publicFileToBuiltUrl(id, config) } - const cache = assetCache.get(config)! + const cache = assetCache.get(environment)! const cached = cache.get(id) if (cached) { return cached @@ -356,7 +358,7 @@ async function fileToBuiltUrl( const content = await fsp.readFile(file) let url: string - if (shouldInline(config, file, id, content, pluginContext, forceInline)) { + if (shouldInline(pluginContext, file, id, content, forceInline)) { if (config.build.lib && isGitLfsPlaceholder(content)) { config.logger.warn( colors.yellow(`Inlined file ${id} was not downloaded via Git LFS`), @@ -383,7 +385,7 @@ async function fileToBuiltUrl( }) const originalName = normalizePath(path.relative(config.root, file)) - generatedAssets.get(config)!.set(referenceId, { originalName }) + generatedAssetsMap.get(environment)!.set(referenceId, { originalName }) url = `__VITE_ASSET__${referenceId}__${postfix ? `$_${postfix}__` : ``}` // TODO_BASE } @@ -393,12 +395,13 @@ async function fileToBuiltUrl( } export async function urlToBuiltUrl( + pluginContext: PluginContext, url: string, importer: string, - config: ResolvedConfig, - pluginContext: PluginContext, forceInline?: boolean, ): Promise { + const environment = pluginContext.environment! + const { config } = environment if (checkPublicFile(url, config)) { return publicFileToBuiltUrl(url, config) } @@ -407,9 +410,8 @@ export async function urlToBuiltUrl( ? path.join(config.root, url) : path.join(path.dirname(importer), url) return fileToBuiltUrl( - file, - config, pluginContext, + file, // skip public check since we just did it above true, forceInline, @@ -417,23 +419,25 @@ export async function urlToBuiltUrl( } const shouldInline = ( - config: ResolvedConfig, + pluginContext: PluginContext, file: string, id: string, content: Buffer, - pluginContext: PluginContext, forceInline: boolean | undefined, ): boolean => { + const environment = pluginContext.environment! + const { config } = environment + const { assetsInlineLimit } = environment.options.build if (config.build.lib) return true if (pluginContext.getModuleInfo(id)?.isEntry) return false if (forceInline !== undefined) return forceInline let limit: number - if (typeof config.build.assetsInlineLimit === 'function') { - const userShouldInline = config.build.assetsInlineLimit(file, content) + if (typeof assetsInlineLimit === 'function') { + const userShouldInline = assetsInlineLimit(file, content) if (userShouldInline != null) return userShouldInline limit = DEFAULT_ASSETS_INLINE_LIMIT } else { - limit = Number(config.build.assetsInlineLimit) + limit = Number(assetsInlineLimit) } if (file.endsWith('.html')) return false // Don't inline SVG with fragments, as they are meant to be reused diff --git a/packages/vite/src/node/plugins/assetImportMetaUrl.ts b/packages/vite/src/node/plugins/assetImportMetaUrl.ts index fd5b4a8e379e8e..9b68ff7553d42a 100644 --- a/packages/vite/src/node/plugins/assetImportMetaUrl.ts +++ b/packages/vite/src/node/plugins/assetImportMetaUrl.ts @@ -126,9 +126,9 @@ export function assetImportMetaUrlPlugin(config: ResolvedConfig): Plugin { try { if (publicDir && isParentDirectory(publicDir, file)) { const publicPath = '/' + path.posix.relative(publicDir, file) - builtUrl = await fileToUrl(publicPath, config, this) + builtUrl = await fileToUrl(this, publicPath) } else { - builtUrl = await fileToUrl(file, config, this) + builtUrl = await fileToUrl(this, file) } } catch { // do nothing, we'll log a warning after this diff --git a/packages/vite/src/node/plugins/css.ts b/packages/vite/src/node/plugins/css.ts index 8304306ad2d896..38556c154a9397 100644 --- a/packages/vite/src/node/plugins/css.ts +++ b/packages/vite/src/node/plugins/css.ts @@ -75,7 +75,7 @@ import { addToHTMLProxyTransformResult } from './html' import { assetUrlRE, fileToUrl, - generatedAssets, + generatedAssetsMap, publicAssetUrlCache, publicAssetUrlRE, publicFileToBuiltUrl, @@ -343,7 +343,7 @@ export function cssPlugin(config: ResolvedConfig): Plugin { } const resolved = await resolveUrl(decodedUrl, importer) if (resolved) { - return fileToUrl(resolved, config, this) + return fileToUrl(this, resolved) } if (config.command === 'build') { const isExternal = config.build.rollupOptions.external @@ -556,6 +556,12 @@ export function cssPostPlugin(config: ResolvedConfig): Plugin { }, async renderChunk(code, chunk, opts) { + const { environment } = this + if (!environment) { + return + } + const generatedAssets = generatedAssetsMap.get(environment)! + let chunkCSS = '' let isPureCssChunk = true const ids = Object.keys(chunk.modules) @@ -710,9 +716,7 @@ export function cssPostPlugin(config: ResolvedConfig): Plugin { type: 'asset', source: content, }) - generatedAssets - .get(config)! - .set(referenceId, { originalName: originalFilename }) + generatedAssets.set(referenceId, { originalName: originalFilename }) const replacement = toOutputFilePathInJS( this.getFileName(referenceId), @@ -767,9 +771,10 @@ export function cssPostPlugin(config: ResolvedConfig): Plugin { type: 'asset', source: chunkCSS, }) - generatedAssets - .get(config)! - .set(referenceId, { originalName: originalFilename, isEntry }) + generatedAssets.set(referenceId, { + originalName: originalFilename, + isEntry, + }) chunk.viteMetadata!.importedCss.add(this.getFileName(referenceId)) } else if (!config.build.ssr) { // legacy build and inline css @@ -783,13 +788,8 @@ export function cssPostPlugin(config: ResolvedConfig): Plugin { chunkCSS = await finalizeCss(chunkCSS, true, config) let cssString = JSON.stringify(chunkCSS) cssString = - renderAssetUrlInJS( - this, - config, - chunk, - opts, - cssString, - )?.toString() || cssString + renderAssetUrlInJS(this, chunk, opts, cssString)?.toString() || + cssString const style = `__vite_style__` const injectCode = `var ${style} = document.createElement('style');` + @@ -980,7 +980,7 @@ export function cssAnalysisPlugin(config: ResolvedConfig): Plugin { ? moduleGraph!.createFileOnlyEntry(file) : await moduleGraph!.ensureEntryFromUrl( stripBase( - await fileToUrl(file, config, this), + await fileToUrl(this, file), (config.server?.origin ?? '') + devBase, ), ), diff --git a/packages/vite/src/node/plugins/html.ts b/packages/vite/src/node/plugins/html.ts index 7d971375040b5c..f386f5b6e05c44 100644 --- a/packages/vite/src/node/plugins/html.ts +++ b/packages/vite/src/node/plugins/html.ts @@ -411,7 +411,7 @@ export function buildHtmlPlugin(config: ResolvedConfig): Plugin { !namedOutput.includes(removeLeadingSlash(url)) // Allow for absolute references as named output can't be an absolute path ) { try { - return await urlToBuiltUrl(url, id, config, this, shouldInline) + return await urlToBuiltUrl(this, url, id, shouldInline) } catch (e) { if (e.code !== 'ENOENT') { throw e @@ -646,7 +646,7 @@ export function buildHtmlPlugin(config: ResolvedConfig): Plugin { s.update( start, end, - partialEncodeURIPath(await urlToBuiltUrl(url, id, config, this)), + partialEncodeURIPath(await urlToBuiltUrl(this, url, id)), ) } } @@ -862,7 +862,7 @@ export function buildHtmlPlugin(config: ResolvedConfig): Plugin { } // inject css link when cssCodeSplit is false - if (!config.build.cssCodeSplit) { + if (this.environment?.options.build.cssCodeSplit === false) { const cssChunk = Object.values(bundle).find( (chunk) => chunk.type === 'asset' && chunk.name === 'style.css', ) as OutputAsset | undefined diff --git a/packages/vite/src/node/plugins/importAnalysisBuild.ts b/packages/vite/src/node/plugins/importAnalysisBuild.ts index f190d18cc0cda4..af6244804e8a4c 100644 --- a/packages/vite/src/node/plugins/importAnalysisBuild.ts +++ b/packages/vite/src/node/plugins/importAnalysisBuild.ts @@ -15,6 +15,7 @@ import { numberToPos, } from '../utils' import type { Plugin } from '../plugin' +import type { Environment } from '../environment' import type { ResolvedConfig } from '../config' import { toOutputFilePathInJS } from '../build' import { genSourceMapUrl } from '../server/sourcemap' @@ -152,14 +153,11 @@ function preload( }) } -/** - * Build only. During serve this is performed as part of ./importAnalysis. - */ -export function buildImportAnalysisPlugin(config: ResolvedConfig): Plugin { - const isWorker = config.isWorker - +function getModulePreloadData(environment: Environment) { + const { modulePreload } = environment.options.build + const { config } = environment const resolveModulePreloadDependencies = - config.build.modulePreload && config.build.modulePreload.resolveDependencies + modulePreload && modulePreload.resolveDependencies const renderBuiltUrl = config.experimental.renderBuiltUrl const customModulePreloadPaths = !!( resolveModulePreloadDependencies || renderBuiltUrl @@ -167,34 +165,17 @@ export function buildImportAnalysisPlugin(config: ResolvedConfig): Plugin { const isRelativeBase = config.base === './' || config.base === '' const optimizeModulePreloadRelativePaths = isRelativeBase && !customModulePreloadPaths + return { + customModulePreloadPaths, + optimizeModulePreloadRelativePaths, + } +} - const { modulePreload } = config.build - const scriptRel = - modulePreload && modulePreload.polyfill - ? `'modulepreload'` - : `(${detectScriptRel.toString()})()` - - // There are three different cases for the preload list format in __vitePreload - // - // __vitePreload(() => import(asyncChunk), [ ...deps... ]) - // - // This is maintained to keep backwards compatibility as some users developed plugins - // using regex over this list to workaround the fact that module preload wasn't - // configurable. - const assetsURL = customModulePreloadPaths - ? // If `experimental.renderBuiltUrl` or `build.modulePreload.resolveDependencies` are used - // the dependencies are already resolved. To avoid the need for `new URL(dep, import.meta.url)` - // a helper `__vitePreloadRelativeDep` is used to resolve from relative paths which can be minimized. - `function(dep, importerUrl) { return dep[0] === '.' ? new URL(dep, importerUrl).href : dep }` - : optimizeModulePreloadRelativePaths - ? // If there isn't custom resolvers affecting the deps list, deps in the list are relative - // to the current chunk and are resolved to absolute URL by the __vitePreload helper itself. - // The importerUrl is passed as third parameter to __vitePreload in this case - `function(dep, importerUrl) { return new URL(dep, importerUrl).href }` - : // If the base isn't relative, then the deps are relative to the projects `outDir` and the base - // is appended inside __vitePreload too. - `function(dep) { return ${JSON.stringify(config.base)}+dep }` - const preloadCode = `const scriptRel = ${scriptRel};const assetsURL = ${assetsURL};const seen = {};export const ${preloadMethod} = ${preload.toString()}` +/** + * Build only. During serve this is performed as part of ./importAnalysis. + */ +export function buildImportAnalysisPlugin(config: ResolvedConfig): Plugin { + const isWorker = config.isWorker return { name: 'vite:build-import-analysis', @@ -205,7 +186,39 @@ export function buildImportAnalysisPlugin(config: ResolvedConfig): Plugin { }, load(id) { - if (id === preloadHelperId) { + const { environment } = this + if (environment && id === preloadHelperId) { + const { modulePreload } = environment.options.build + + const { customModulePreloadPaths, optimizeModulePreloadRelativePaths } = + getModulePreloadData(environment) + + const scriptRel = + modulePreload && modulePreload.polyfill + ? `'modulepreload'` + : `(${detectScriptRel.toString()})()` + + // There are three different cases for the preload list format in __vitePreload + // + // __vitePreload(() => import(asyncChunk), [ ...deps... ]) + // + // This is maintained to keep backwards compatibility as some users developed plugins + // using regex over this list to workaround the fact that module preload wasn't + // configurable. + const assetsURL = customModulePreloadPaths + ? // If `experimental.renderBuiltUrl` or `build.modulePreload.resolveDependencies` are used + // the dependencies are already resolved. To avoid the need for `new URL(dep, import.meta.url)` + // a helper `__vitePreloadRelativeDep` is used to resolve from relative paths which can be minimized. + `function(dep, importerUrl) { return dep[0] === '.' ? new URL(dep, importerUrl).href : dep }` + : optimizeModulePreloadRelativePaths + ? // If there isn't custom resolvers affecting the deps list, deps in the list are relative + // to the current chunk and are resolved to absolute URL by the __vitePreload helper itself. + // The importerUrl is passed as third parameter to __vitePreload in this case + `function(dep, importerUrl) { return new URL(dep, importerUrl).href }` + : // If the base isn't relative, then the deps are relative to the projects `outDir` and the base + // is appended inside __vitePreload too. + `function(dep) { return ${JSON.stringify(config.base)}+dep }` + const preloadCode = `const scriptRel = ${scriptRel};const assetsURL = ${assetsURL};const seen = {};export const ${preloadMethod} = ${preload.toString()}` return preloadCode } }, @@ -244,6 +257,9 @@ export function buildImportAnalysisPlugin(config: ResolvedConfig): Plugin { const ssr = environment.options.build.ssr const insertPreload = !(ssr || !!config.build.lib || isWorker) + const { customModulePreloadPaths, optimizeModulePreloadRelativePaths } = + getModulePreloadData(environment) + for (let index = 0; index < imports.length; index++) { const { e: end, @@ -322,6 +338,9 @@ export function buildImportAnalysisPlugin(config: ResolvedConfig): Plugin { return } const buildSourcemap = environment.options.build.sourcemap + const { modulePreload } = environment.options.build + const { customModulePreloadPaths, optimizeModulePreloadRelativePaths } = + getModulePreloadData(environment) for (const file in bundle) { const chunk = bundle[file] diff --git a/packages/vite/src/node/plugins/manifest.ts b/packages/vite/src/node/plugins/manifest.ts index 84602e78268866..fe92c8df193b47 100644 --- a/packages/vite/src/node/plugins/manifest.ts +++ b/packages/vite/src/node/plugins/manifest.ts @@ -5,10 +5,9 @@ import type { OutputChunk, RenderedChunk, } from 'rollup' -import type { ResolvedConfig } from '..' import type { Plugin } from '../plugin' import { normalizePath, sortObjectKeys } from '../utils' -import { generatedAssets } from './asset' +import { generatedAssetsMap } from './asset' import type { GeneratedAssetMeta } from './asset' const endsWithJSRE = /\.[cm]?js$/ @@ -27,7 +26,7 @@ export interface ManifestChunk { dynamicImports?: string[] } -export function manifestPlugin(config: ResolvedConfig): Plugin { +export function manifestPlugin(): Plugin { const manifest: Manifest = {} let outputCount: number @@ -40,8 +39,15 @@ export function manifestPlugin(config: ResolvedConfig): Plugin { }, generateBundle({ format }, bundle) { + const { environment } = this + if (!environment) { + return + } + const { root } = environment.config + const buildOptions = environment.options.build + function getChunkName(chunk: OutputChunk) { - return getChunkOriginalFileName(chunk, config.root, format) + return getChunkOriginalFileName(chunk, root, format) } function getInternalImports(imports: string[]): string[] { @@ -112,7 +118,7 @@ export function manifestPlugin(config: ResolvedConfig): Plugin { } const fileNameToAssetMeta = new Map() - const assets = generatedAssets.get(config)! + const assets = generatedAssetsMap.get(environment)! assets.forEach((asset, referenceId) => { try { const fileName = this.getFileName(referenceId) @@ -158,13 +164,13 @@ export function manifestPlugin(config: ResolvedConfig): Plugin { }) outputCount++ - const output = config.build.rollupOptions?.output + const output = buildOptions.rollupOptions?.output const outputLength = Array.isArray(output) ? output.length : 1 if (outputCount >= outputLength) { this.emitFile({ fileName: - typeof config.build.manifest === 'string' - ? config.build.manifest + typeof buildOptions.manifest === 'string' + ? buildOptions.manifest : '.vite/manifest.json', type: 'asset', source: JSON.stringify(sortObjectKeys(manifest), undefined, 2), diff --git a/packages/vite/src/node/plugins/wasm.ts b/packages/vite/src/node/plugins/wasm.ts index f5adab8e1b43d5..22ab2ab00eade4 100644 --- a/packages/vite/src/node/plugins/wasm.ts +++ b/packages/vite/src/node/plugins/wasm.ts @@ -65,7 +65,7 @@ export const wasmHelperPlugin = (config: ResolvedConfig): Plugin => { return } - const url = await fileToUrl(id, config, this) + const url = await fileToUrl(this, id) return ` import initWasm from "${wasmHelperId}" diff --git a/packages/vite/src/node/plugins/worker.ts b/packages/vite/src/node/plugins/worker.ts index 6ac5f470b65082..0d38b559ad820e 100644 --- a/packages/vite/src/node/plugins/worker.ts +++ b/packages/vite/src/node/plugins/worker.ts @@ -69,8 +69,9 @@ async function bundleWorkerEntry( // bundle the file as entry to support imports const { rollup } = await import('rollup') const { plugins, rollupOptions, format } = config.worker - const workerEnvironment = new BuildEnvironment('client', config) // TODO: should this be 'worker'? - const resolvedPlugins = await plugins(newBundleChain) + const { plugins: resolvedPlugins, config: workerConfig } = + await plugins(newBundleChain) + const workerEnvironment = new BuildEnvironment('client', workerConfig) // TODO: should this be 'worker'? const bundle = await rollup({ ...rollupOptions, input, @@ -356,7 +357,7 @@ export function webWorkerPlugin(config: ResolvedConfig): Plugin { urlCode = JSON.stringify(await workerFileToUrl(config, id)) } } else { - let url = await fileToUrl(cleanUrl(id), config, this) + let url = await fileToUrl(this, cleanUrl(id)) url = injectQuery(url, `${WORKER_FILE_ID}&type=${workerType}`) urlCode = JSON.stringify(url) } diff --git a/packages/vite/src/node/plugins/workerImportMetaUrl.ts b/packages/vite/src/node/plugins/workerImportMetaUrl.ts index 53f867a004a4b1..ebae94e14d38ab 100644 --- a/packages/vite/src/node/plugins/workerImportMetaUrl.ts +++ b/packages/vite/src/node/plugins/workerImportMetaUrl.ts @@ -182,7 +182,7 @@ export function workerImportMetaUrlPlugin(config: ResolvedConfig): Plugin { if (isBuild) { builtUrl = await workerFileToUrl(config, file) } else { - builtUrl = await fileToUrl(cleanUrl(file), config, this) + builtUrl = await fileToUrl(this, cleanUrl(file)) builtUrl = injectQuery( builtUrl, `${WORKER_FILE_ID}&type=${workerType}`,