From dee6067ec78c9f9d7923d780b4941d835b34fcf4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=BF=A0=20/=20green?= Date: Wed, 18 Oct 2023 01:54:47 +0900 Subject: [PATCH] feat!: rollup v4 (#14508) --- docs/guide/migration.md | 11 + package.json | 2 +- packages/create-vite/build.config.ts | 1 + packages/vite/LICENSE.md | 7 - packages/vite/package.json | 3 +- packages/vite/rollup.config.ts | 1 + packages/vite/src/node/build.ts | 5 +- packages/vite/src/node/plugin.ts | 2 +- packages/vite/src/node/plugins/asset.ts | 10 +- packages/vite/src/node/plugins/ensureWatch.ts | 17 -- .../vite/src/node/plugins/importAnalysis.ts | 6 +- .../src/node/plugins/importAnalysisBuild.ts | 10 +- .../vite/src/node/plugins/importMetaGlob.ts | 2 +- packages/vite/src/node/plugins/index.ts | 3 - .../vite/src/node/plugins/loadFallback.ts | 10 +- .../vite/src/node/plugins/optimizedDeps.ts | 5 +- packages/vite/src/node/plugins/preAlias.ts | 1 - .../vite/src/node/server/pluginContainer.ts | 42 +--- packages/vite/src/node/server/sourcemap.ts | 7 +- .../vite/src/node/server/transformRequest.ts | 6 +- .../node/ssr/__tests__/ssrTransform.spec.ts | 6 +- packages/vite/src/node/ssr/ssrTransform.ts | 11 +- packages/vite/tsconfig.base.json | 2 +- playground/assets/__tests__/assets.spec.ts | 12 +- .../relative-base-assets.spec.ts | 10 +- .../runtime-base/runtime-base-assets.spec.ts | 12 +- .../url-base/url-base-assets.spec.ts | 12 +- .../__tests__/backend-integration.spec.ts | 2 +- .../__tests__/lightningcss.spec.ts | 2 +- playground/css/__tests__/css.spec.ts | 14 +- .../no-css-minify/no-css-minify.spec.ts | 4 +- .../glob-import/__tests__/glob-import.spec.ts | 2 +- playground/legacy/__tests__/legacy.spec.ts | 12 +- playground/lib/__tests__/lib.spec.ts | 2 +- .../preload-disabled/preload-disabled.spec.ts | 2 +- playground/preload/__tests__/preload.spec.ts | 4 +- .../resolve-deps/preload-resolve-deps.spec.ts | 4 +- .../__tests__/ssr-webworker.spec.ts | 2 +- .../sourcemap-hidden-worker.spec.ts | 26 ++- .../sourcemap-inline-worker.spec.ts | 12 +- .../sourcemap/sourcemap-worker.spec.ts | 38 ++-- pnpm-lock.yaml | 213 ++++++++++++------ 42 files changed, 294 insertions(+), 261 deletions(-) delete mode 100644 packages/vite/src/node/plugins/ensureWatch.ts diff --git a/docs/guide/migration.md b/docs/guide/migration.md index 813e4c2139b02d..9d8932f6577241 100644 --- a/docs/guide/migration.md +++ b/docs/guide/migration.md @@ -4,6 +4,17 @@ Vite no longer supports Node.js 14 / 16 / 17 / 19, which reached its EOL. Node.js 18 / 20+ is now required. +## Rollup 4 + +Vite is now using Rollup 4 which also brings along its breaking changes, in particular: + +- Import assertions (`assertions` prop) has been renamed to import attributes (`attributes` prop). +- Acorn plugins are no longer supported. +- For Vite plugins, `this.resolve` `skipSelf` option is now `true` by default. +- For Vite plugins, `this.parse` now only supports the `allowReturnOutsideFunction` option for now. + +Read the full breaking changes in [Rollup's release notes](https://github.com/rollup/rollup/releases/tag/v4.0.0) for build-related changes in `build.rollupOptions`. + ## Deprecate CJS Node API The CJS Node API of Vite is deprecated. When calling `require('vite')`, a deprecation warning is now logged. You should update your files or frameworks to import the ESM build of Vite instead. diff --git a/package.json b/package.json index c81132db2c3245..36f8606a8319bc 100644 --- a/package.json +++ b/package.json @@ -76,7 +76,7 @@ "playwright-chromium": "^1.39.0", "prettier": "3.0.3", "rimraf": "^5.0.5", - "rollup": "^3.29.2", + "rollup": "^4.1.4", "simple-git-hooks": "^2.9.0", "tslib": "^2.6.2", "tsx": "^3.13.0", diff --git a/packages/create-vite/build.config.ts b/packages/create-vite/build.config.ts index 71d1ba88717d6d..03907ba7e0d809 100644 --- a/packages/create-vite/build.config.ts +++ b/packages/create-vite/build.config.ts @@ -23,6 +23,7 @@ export default defineBuildConfig({ 'rollup:options'(ctx, options) { options.plugins = [ options.plugins, + // @ts-expect-error TODO: unbuild uses rollup v3 and Vite uses rollup v4 licensePlugin( path.resolve(__dirname, './LICENSE'), 'create-vite license', diff --git a/packages/vite/LICENSE.md b/packages/vite/LICENSE.md index 3a5cb6fc137d51..286af89af35c42 100644 --- a/packages/vite/LICENSE.md +++ b/packages/vite/LICENSE.md @@ -566,13 +566,6 @@ Repository: https://github.com/acornjs/acorn.git --------------------------------------- -## acorn-import-assertions -License: MIT -By: Sven Sauleau -Repository: https://github.com/xtuc/acorn-import-assertions - ---------------------------------------- - ## acorn-walk License: MIT By: Marijn Haverbeke, Ingvar Stepanyan, Adrian Heine diff --git a/packages/vite/package.json b/packages/vite/package.json index 158704cea05caa..c768c6a38a1cba 100644 --- a/packages/vite/package.json +++ b/packages/vite/package.json @@ -76,7 +76,7 @@ "dependencies": { "esbuild": "^0.19.3", "postcss": "^8.4.31", - "rollup": "^3.29.4" + "rollup": "^4.1.4" }, "optionalDependencies": { "fsevents": "~2.3.3" @@ -94,7 +94,6 @@ "@types/escape-html": "^1.0.2", "@types/pnpapi": "^0.0.3", "acorn": "^8.10.0", - "acorn-import-assertions": "^1.9.0", "acorn-walk": "^8.2.0", "cac": "^6.7.14", "chokidar": "^3.5.3", diff --git a/packages/vite/rollup.config.ts b/packages/vite/rollup.config.ts index 80222d58184c93..598a7fbc4c6b37 100644 --- a/packages/vite/rollup.config.ts +++ b/packages/vite/rollup.config.ts @@ -161,6 +161,7 @@ function createNodeConfig(isProduction: boolean) { external: [ 'fsevents', 'lightningcss', + 'rollup/parseAst', ...Object.keys(pkg.dependencies), ...(isProduction ? [] : Object.keys(pkg.devDependencies)), ], diff --git a/packages/vite/src/node/build.ts b/packages/vite/src/node/build.ts index c1f5821e4a7b40..49617b16de9ac2 100644 --- a/packages/vite/src/node/build.ts +++ b/packages/vite/src/node/build.ts @@ -14,7 +14,6 @@ import type { RollupLog, RollupOptions, RollupOutput, - RollupWarning, RollupWatcher, WatcherOptions, } from 'rollup' @@ -45,7 +44,6 @@ import { initDepsOptimizer } from './optimizer' import { loadFallbackPlugin } from './plugins/loadFallback' import { findNearestPackageData } from './packages' import type { PackageCache } from './packages' -import { ensureWatchPlugin } from './plugins/ensureWatch' import { ESBUILD_MODULES_TARGET, VERSION } from './constants' import { resolveChokidarOptions } from './watch' import { completeSystemWrapPlugin } from './plugins/completeSystemWrap' @@ -426,7 +424,6 @@ export async function resolveBuildPlugins(config: ResolvedConfig): Promise<{ return { pre: [ completeSystemWrapPlugin(), - ...(options.watch ? [ensureWatchPlugin()] : []), ...(usePluginCommonjs ? [commonjsPlugin(options.commonjsOptions)] : []), dataURIPlugin(), ...(( @@ -858,7 +855,7 @@ const dynamicImportWarningIgnoreList = [ ] export function onRollupWarning( - warning: RollupWarning, + warning: RollupLog, warn: LoggingFunction, config: ResolvedConfig, ): void { diff --git a/packages/vite/src/node/plugin.ts b/packages/vite/src/node/plugin.ts index c58749b58479c9..e6e5e4d80f701d 100644 --- a/packages/vite/src/node/plugin.ts +++ b/packages/vite/src/node/plugin.ts @@ -150,7 +150,7 @@ export interface Plugin extends RollupPlugin { source: string, importer: string | undefined, options: { - assertions: Record + attributes: Record custom?: CustomPluginOptions ssr?: boolean /** diff --git a/packages/vite/src/node/plugins/asset.ts b/packages/vite/src/node/plugins/asset.ts index ce559f419f318e..89ff347c017244 100644 --- a/packages/vite/src/node/plugins/asset.ts +++ b/packages/vite/src/node/plugins/asset.ts @@ -27,7 +27,8 @@ import { } from '../utils' import { FS_PREFIX } from '../constants' -export const assetUrlRE = /__VITE_ASSET__([a-z\d]+)__(?:\$_(.*?)__)?/g +// referenceId is base64url but replaces - with $ +export const assetUrlRE = /__VITE_ASSET__([\w$]+)__(?:\$_(.*?)__)?/g const rawRE = /(?:\?|&)raw(?:&|$)/ export const urlRE = /(\?|&)url(?:&|$)/ @@ -78,10 +79,10 @@ export function renderAssetUrlInJS( let s: MagicString | undefined // Urls added with JS using e.g. - // imgElement.src = "__VITE_ASSET__5aa0ddc0__" are using quotes + // imgElement.src = "__VITE_ASSET__5aA0Ddc0__" are using quotes // Urls added in CSS that is imported in JS end up like - // var inlined = ".inlined{color:green;background:url(__VITE_ASSET__5aa0ddc0__)}\n"; + // var inlined = ".inlined{color:green;background:url(__VITE_ASSET__5aA0Ddc0__)}\n"; // In both cases, the wrapping should already be fine @@ -107,7 +108,7 @@ export function renderAssetUrlInJS( s.update(match.index, match.index + full.length, replacementString) } - // Replace __VITE_PUBLIC_ASSET__5aa0ddc0__ with absolute paths + // Replace __VITE_PUBLIC_ASSET__5aA0Ddc0__ with absolute paths const publicAssetUrlMap = publicAssetUrlCache.get(config)! publicAssetUrlRE.lastIndex = 0 @@ -179,6 +180,7 @@ export function assetPlugin(config: ResolvedConfig): Plugin { // raw requests, read from disk if (rawRE.test(id)) { const file = checkPublicFile(id, config) || cleanUrl(id) + this.addWatchFile(file) // raw query, read file and return as string return `export default ${JSON.stringify( await fsp.readFile(file, 'utf-8'), diff --git a/packages/vite/src/node/plugins/ensureWatch.ts b/packages/vite/src/node/plugins/ensureWatch.ts deleted file mode 100644 index d20c4dedc8f354..00000000000000 --- a/packages/vite/src/node/plugins/ensureWatch.ts +++ /dev/null @@ -1,17 +0,0 @@ -import type { Plugin } from '../plugin' -import { cleanUrl, queryRE } from '../utils' - -/** - * plugin to ensure rollup can watch correctly. - */ -export function ensureWatchPlugin(): Plugin { - return { - name: 'vite:ensure-watch', - load(id) { - if (queryRE.test(id)) { - this.addWatchFile(cleanUrl(id)) - } - return null - }, - } -} diff --git a/packages/vite/src/node/plugins/importAnalysis.ts b/packages/vite/src/node/plugins/importAnalysis.ts index 0681a38caf63d7..88832054df44c4 100644 --- a/packages/vite/src/node/plugins/importAnalysis.ts +++ b/packages/vite/src/node/plugins/importAnalysis.ts @@ -408,7 +408,7 @@ export function importAnalysisPlugin(config: ResolvedConfig): Plugin { ss: expStart, se: expEnd, d: dynamicIndex, - a: assertIndex, + a: attributeIndex, } = importSpecifier // #2083 User may use escape path, @@ -464,8 +464,8 @@ export function importAnalysisPlugin(config: ResolvedConfig): Plugin { const isDynamicImport = dynamicIndex > -1 - // strip import assertions as we can process them ourselves - if (!isDynamicImport && assertIndex > -1) { + // strip import attributes as we can process them ourselves + if (!isDynamicImport && attributeIndex > -1) { str().remove(end + 1, expEnd) } diff --git a/packages/vite/src/node/plugins/importAnalysisBuild.ts b/packages/vite/src/node/plugins/importAnalysisBuild.ts index 822b99d43ead18..918a219f322a75 100644 --- a/packages/vite/src/node/plugins/importAnalysisBuild.ts +++ b/packages/vite/src/node/plugins/importAnalysisBuild.ts @@ -261,7 +261,9 @@ export function buildImportAnalysisPlugin(config: ResolvedConfig): Plugin { } } - const resolved = await this.resolve(url, importerFile) + const resolved = await this.resolve(url, importerFile, { + skipSelf: false, + }) if (!resolved) { // in ssr, we should let node handle the missing modules @@ -305,13 +307,13 @@ export function buildImportAnalysisPlugin(config: ResolvedConfig): Plugin { se: expEnd, n: specifier, d: dynamicIndex, - a: assertIndex, + a: attributeIndex, } = imports[index] const isDynamicImport = dynamicIndex > -1 - // strip import assertions as we can process them ourselves - if (!isDynamicImport && assertIndex > -1) { + // strip import attributes as we can process them ourselves + if (!isDynamicImport && attributeIndex > -1) { str().remove(end + 1, expEnd) } diff --git a/packages/vite/src/node/plugins/importMetaGlob.ts b/packages/vite/src/node/plugins/importMetaGlob.ts index c3633ac83d15b8..695e6fada9d713 100644 --- a/packages/vite/src/node/plugins/importMetaGlob.ts +++ b/packages/vite/src/node/plugins/importMetaGlob.ts @@ -486,7 +486,7 @@ type IdResolver = ( id: string, importer?: string, options?: { - assertions?: Record + attributes?: Record custom?: CustomPluginOptions isEntry?: boolean skipSelf?: boolean diff --git a/packages/vite/src/node/plugins/index.ts b/packages/vite/src/node/plugins/index.ts index 28d88c825fbb3a..4279d99484d379 100644 --- a/packages/vite/src/node/plugins/index.ts +++ b/packages/vite/src/node/plugins/index.ts @@ -21,7 +21,6 @@ import { preAliasPlugin } from './preAlias' import { definePlugin } from './define' import { workerImportMetaUrlPlugin } from './workerImportMetaUrl' import { assetImportMetaUrlPlugin } from './assetImportMetaUrl' -import { ensureWatchPlugin } from './ensureWatch' import { metadataPlugin } from './metadata' import { dynamicImportVarsPlugin } from './dynamicImportVars' import { importGlobPlugin } from './importMetaGlob' @@ -33,7 +32,6 @@ export async function resolvePlugins( postPlugins: Plugin[], ): Promise { const isBuild = config.command === 'build' - const isWatch = isBuild && !!config.build.watch const buildPlugins = isBuild ? await (await import('../build')).resolveBuildPlugins(config) : { pre: [], post: [] } @@ -48,7 +46,6 @@ export async function resolvePlugins( : optimizedDepsPlugin(config), ] : []), - isWatch ? ensureWatchPlugin() : null, isBuild ? metadataPlugin() : null, watchPackageDataPlugin(config.packageCache), preAliasPlugin(config), diff --git a/packages/vite/src/node/plugins/loadFallback.ts b/packages/vite/src/node/plugins/loadFallback.ts index b806f8b93ac201..9274622dff5528 100644 --- a/packages/vite/src/node/plugins/loadFallback.ts +++ b/packages/vite/src/node/plugins/loadFallback.ts @@ -10,10 +10,14 @@ export function loadFallbackPlugin(): Plugin { name: 'vite:load-fallback', async load(id) { try { - // if we don't add `await` here, we couldn't catch the error in readFile - return await fsp.readFile(cleanUrl(id), 'utf-8') + const cleanedId = cleanUrl(id) + const content = await fsp.readFile(cleanedId, 'utf-8') + this.addWatchFile(cleanedId) + return content } catch (e) { - return fsp.readFile(id, 'utf-8') + const content = await fsp.readFile(id, 'utf-8') + this.addWatchFile(id) + return content } }, } diff --git a/packages/vite/src/node/plugins/optimizedDeps.ts b/packages/vite/src/node/plugins/optimizedDeps.ts index 7bb1e040517320..1086ab73d10046 100644 --- a/packages/vite/src/node/plugins/optimizedDeps.ts +++ b/packages/vite/src/node/plugins/optimizedDeps.ts @@ -102,10 +102,7 @@ export function optimizedDepsBuildPlugin(config: ResolvedConfig): Plugin { // When a optimized dep is aliased, we need to avoid waiting for it before optimizing return } - const resolved = await this.resolve(id, importer, { - ...options, - skipSelf: true, - }) + const resolved = await this.resolve(id, importer, options) if (resolved && !resolved.external) { depsOptimizer.delayDepsOptimizerUntil(resolved.id, async () => { await this.load(resolved) diff --git a/packages/vite/src/node/plugins/preAlias.ts b/packages/vite/src/node/plugins/preAlias.ts index cd86bac770d823..029bca0ac9f067 100644 --- a/packages/vite/src/node/plugins/preAlias.ts +++ b/packages/vite/src/node/plugins/preAlias.ts @@ -56,7 +56,6 @@ export function preAliasPlugin(config: ResolvedConfig): Plugin { const resolved = await this.resolve(id, importer, { ...options, custom: { ...options.custom, 'vite:pre-alias': true }, - skipSelf: true, }) if (resolved && !depsOptimizer.isOptimizedDepFile(resolved.id)) { const optimizeDeps = depsOptimizer.options diff --git a/packages/vite/src/node/server/pluginContainer.ts b/packages/vite/src/node/server/pluginContainer.ts index 76985d93b0cf5d..4b36fe5aa86ee6 100644 --- a/packages/vite/src/node/server/pluginContainer.ts +++ b/packages/vite/src/node/server/pluginContainer.ts @@ -33,6 +33,7 @@ import fs from 'node:fs' import { join } from 'node:path' import { performance } from 'node:perf_hooks' import { VERSION as rollupVersion } from 'rollup' +import { parseAst as rollupParseAst } from 'rollup/parseAst' import type { AsyncPluginHooks, CustomPluginOptions, @@ -56,18 +57,14 @@ import type { SourceMap, TransformResult, } from 'rollup' -import * as acorn from 'acorn' import type { RawSourceMap } from '@ampproject/remapping' import { TraceMap, originalPositionFor } from '@jridgewell/trace-mapping' -// @ts-expect-error untyped -import { importAssertions } from 'acorn-import-assertions' import MagicString from 'magic-string' import type { FSWatcher } from 'chokidar' import colors from 'picocolors' import type * as postcss from 'postcss' import type { Plugin } from '../plugin' import { - arraify, cleanUrl, combineSourcemaps, createDebugger, @@ -116,7 +113,7 @@ export interface PluginContainer { id: string, importer?: string, options?: { - assertions?: Record + attributes?: Record custom?: CustomPluginOptions skip?: Set ssr?: boolean @@ -147,13 +144,9 @@ export interface PluginContainer { type PluginContext = Omit< RollupPluginContext, // not documented - | 'cache' - // deprecated - | 'moduleIds' + 'cache' > -export let parser = acorn.Parser.extend(importAssertions) - export async function createPluginContainer( config: ResolvedConfig, moduleGraph?: ModuleGraph, @@ -294,32 +287,27 @@ export async function createPluginContainer( this._activePlugin = initialPlugin || null } - parse(code: string, opts: any = {}) { - return parser.parse(code, { - sourceType: 'module', - ecmaVersion: 'latest', - locations: true, - ...opts, - }) + parse(code: string, opts: any) { + return rollupParseAst(code, opts) } async resolve( id: string, importer?: string, options?: { - assertions?: Record + attributes?: Record custom?: CustomPluginOptions isEntry?: boolean skipSelf?: boolean }, ) { let skip: Set | undefined - if (options?.skipSelf && this._activePlugin) { + if (options?.skipSelf !== false && this._activePlugin) { skip = new Set(this._resolveSkips) skip.add(this._activePlugin) } let out = await container.resolveId(id, importer, { - assertions: options?.assertions, + attributes: options?.attributes, custom: options?.custom, isEntry: !!options?.isEntry, skip, @@ -628,17 +616,7 @@ export async function createPluginContainer( optionsHook.call(minimalContext, options), )) || options } - if (options.acornInjectPlugins) { - parser = acorn.Parser.extend( - importAssertions, - ...(arraify(options.acornInjectPlugins) as any), - ) - } - return { - acorn, - acornInjectPlugins: [], - ...options, - } + return options })(), getModuleInfo, @@ -678,7 +656,7 @@ export async function createPluginContainer( : plugin.resolveId const result = await handleHookPromise( handler.call(ctx as any, rawId, importer, { - assertions: options?.assertions ?? {}, + attributes: options?.attributes ?? {}, custom: options?.custom, isEntry: !!options?.isEntry, ssr, diff --git a/packages/vite/src/node/server/sourcemap.ts b/packages/vite/src/node/server/sourcemap.ts index 6a8d876c26dbc7..c8f2c8d88fdacd 100644 --- a/packages/vite/src/node/server/sourcemap.ts +++ b/packages/vite/src/node/server/sourcemap.ts @@ -1,7 +1,6 @@ import path from 'node:path' import fsp from 'node:fs/promises' import type { ExistingRawSourceMap, SourceMap } from 'rollup' -import type { SourceMap as MagicStringSourceMap } from 'magic-string' import type { Logger } from '../logger' import { createDebugger } from '../utils' @@ -66,9 +65,7 @@ export async function injectSourcesContent( } } -export function genSourceMapUrl( - map: SourceMap | MagicStringSourceMap | string, -): string { +export function genSourceMapUrl(map: SourceMap | string): string { if (typeof map !== 'string') { map = JSON.stringify(map) } @@ -78,7 +75,7 @@ export function genSourceMapUrl( export function getCodeWithSourcemap( type: 'js' | 'css', code: string, - map: SourceMap | MagicStringSourceMap, + map: SourceMap, ): string { if (debug) { code += `\n/*${JSON.stringify(map, null, 2).replace(/\*\//g, '*\\/')}*/\n` diff --git a/packages/vite/src/node/server/transformRequest.ts b/packages/vite/src/node/server/transformRequest.ts index cbc0b768f70198..69304c7f957850 100644 --- a/packages/vite/src/node/server/transformRequest.ts +++ b/packages/vite/src/node/server/transformRequest.ts @@ -10,7 +10,6 @@ import { blankReplacer, cleanUrl, createDebugger, - ensureWatchedFile, isObject, prettifyUrl, removeTimestampQuery, @@ -174,8 +173,8 @@ async function loadAndTransform( mod?: ModuleNode, resolved?: PartialResolvedId, ) { - const { config, pluginContainer, moduleGraph, watcher } = server - const { root, logger } = config + const { config, pluginContainer, moduleGraph } = server + const { logger } = config const prettyUrl = debugLoad || debugTransform ? prettifyUrl(url, config.root) : '' const ssr = !!options.ssr @@ -263,7 +262,6 @@ async function loadAndTransform( // ensure module in graph after successful load mod ??= await moduleGraph._ensureEntryFromUrl(url, ssr, undefined, resolved) - ensureWatchedFile(watcher, mod.file, root) // transform const transformStart = debugTransform ? performance.now() : 0 diff --git a/packages/vite/src/node/ssr/__tests__/ssrTransform.spec.ts b/packages/vite/src/node/ssr/__tests__/ssrTransform.spec.ts index b2414752ab0444..1afcb3ed5599dd 100644 --- a/packages/vite/src/node/ssr/__tests__/ssrTransform.spec.ts +++ b/packages/vite/src/node/ssr/__tests__/ssrTransform.spec.ts @@ -938,14 +938,14 @@ const Baz = class extends Foo {} test('import assertion attribute', async () => { expect( await ssrTransformSimpleCode(` - import * as foo from './foo.json' assert { type: 'json' }; - import('./bar.json', { assert: { type: 'json' } }); + import * as foo from './foo.json' with { type: 'json' }; + import('./bar.json', { with: { type: 'json' } }); `), ).toMatchInlineSnapshot(` "const __vite_ssr_import_0__ = await __vite_ssr_import__(\\"./foo.json\\"); - __vite_ssr_dynamic_import__('./bar.json', { assert: { type: 'json' } }); + __vite_ssr_dynamic_import__('./bar.json', { with: { type: 'json' } }); "`) }) diff --git a/packages/vite/src/node/ssr/ssrTransform.ts b/packages/vite/src/node/ssr/ssrTransform.ts index 90b29026e9aa38..bb6dbb35657b5b 100644 --- a/packages/vite/src/node/ssr/ssrTransform.ts +++ b/packages/vite/src/node/ssr/ssrTransform.ts @@ -12,8 +12,8 @@ import type { import { extract_names as extractNames } from 'periscopic' import { walk as eswalk } from 'estree-walker' import type { RawSourceMap } from '@ampproject/remapping' +import { parseAst as rollupParseAst } from 'rollup/parseAst' import type { TransformResult } from '../server/transformRequest' -import { parser } from '../server/pluginContainer' import { combineSourcemaps } from '../utils' import { isJSONRequest } from '../plugins/json' @@ -71,12 +71,7 @@ async function ssrTransformScript( let ast: any try { - ast = parser.parse(code, { - sourceType: 'module', - ecmaVersion: 'latest', - locations: true, - allowHashBang: true, - }) + ast = rollupParseAst(code) } catch (err) { if (!err.loc || !err.loc.line) throw err const line = err.loc.line @@ -274,7 +269,7 @@ async function ssrTransformScript( }, }) - let map = s.generateMap({ hires: 'boundary' }) as SourceMap + let map = s.generateMap({ hires: 'boundary' }) if ( inMap && inMap.mappings && diff --git a/packages/vite/tsconfig.base.json b/packages/vite/tsconfig.base.json index 04df5b8dd6f5d7..15fcd2c74e2a9e 100644 --- a/packages/vite/tsconfig.base.json +++ b/packages/vite/tsconfig.base.json @@ -2,7 +2,7 @@ "compilerOptions": { "target": "ES2022", "module": "ESNext", - "moduleResolution": "node", + "moduleResolution": "Bundler", "strict": true, "declaration": true, "noImplicitOverride": true, diff --git a/playground/assets/__tests__/assets.spec.ts b/playground/assets/__tests__/assets.spec.ts index 224c4ae9e36200..fec182a6e8048c 100644 --- a/playground/assets/__tests__/assets.spec.ts +++ b/playground/assets/__tests__/assets.spec.ts @@ -20,7 +20,7 @@ import { } from '~utils' const assetMatch = isBuild - ? /\/foo\/bar\/assets\/asset-\w{8}\.png/ + ? /\/foo\/bar\/assets\/asset-[-\w]{8}\.png/ : '/foo/bar/nested/asset.png' const iconMatch = `/foo/bar/icon.png` @@ -262,7 +262,7 @@ describe('image', () => { srcset.split(', ').forEach((s) => { expect(s).toMatch( isBuild - ? /\/foo\/bar\/assets\/asset-\w{8}\.png \dx/ + ? /\/foo\/bar\/assets\/asset-[-\w]{8}\.png \dx/ : /\/foo\/bar\/nested\/asset.png \dx/, ) }) @@ -393,7 +393,7 @@ test('new URL(`./${dynamic}?abc`, import.meta.url)', async () => { ) expect(await page.textContent('.dynamic-import-meta-url-2-query')).toMatch( isBuild - ? /\/foo\/bar\/assets\/asset-\w{8}\.png\?abc/ + ? /\/foo\/bar\/assets\/asset-[-\w]{8}\.png\?abc/ : '/foo/bar/nested/asset.png?abc', ) }) @@ -404,7 +404,7 @@ test('new URL(`./${1 === 0 ? static : dynamic}?abc`, import.meta.url)', async () ) expect(await page.textContent('.dynamic-import-meta-url-2-ternary')).toMatch( isBuild - ? /\/foo\/bar\/assets\/asset-\w{8}\.png\?abc/ + ? /\/foo\/bar\/assets\/asset-[-\w]{8}\.png\?abc/ : '/foo/bar/nested/asset.png?abc', ) }) @@ -437,7 +437,7 @@ describe.runIf(isBuild)('css and assets in css in build watch', () => { test('css will not be lost and css does not contain undefined', async () => { editFile('index.html', (code) => code.replace('Assets', 'assets'), true) await notifyRebuildComplete(watcher) - const cssFile = findAssetFile(/index-\w+\.css$/, 'foo') + const cssFile = findAssetFile(/index-[-\w]+\.css$/, 'foo') expect(cssFile).not.toBe('') expect(cssFile).not.toMatch(/undefined/) }) @@ -501,6 +501,6 @@ test('url() contains file in publicDir, as inline style', async () => { test.runIf(isBuild)('assets inside