Skip to content

Commit

Permalink
feat: rollup 3 (#9870)
Browse files Browse the repository at this point in the history
Co-authored-by: bluwy <[email protected]>
  • Loading branch information
patak-dev and bluwy authored Nov 7, 2022
1 parent d9f6dc0 commit beb7166
Show file tree
Hide file tree
Showing 18 changed files with 115 additions and 132 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@
"prompts": "^2.4.2",
"resolve": "^1.22.1",
"rimraf": "^3.0.2",
"rollup": "^2.79.1",
"rollup": "~3.2.3",
"rollup-plugin-license": "^2.9.0",
"semver": "^7.3.8",
"simple-git-hooks": "^2.8.1",
Expand Down
2 changes: 1 addition & 1 deletion packages/plugin-legacy/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -415,7 +415,7 @@ function viteLegacyPlugin(options: Options = {}): Plugin[] {
configFile: false,
compact: !!config.build.minify,
sourceMaps,
inputSourceMap: sourceMaps ? chunk.map : undefined,
inputSourceMap: undefined, // sourceMaps ? chunk.map : undefined, `.map` TODO: moved to OutputChunk?
presets: [
// forcing our plugin to run before preset-env by wrapping it in a
// preset so we can catch the injected import statements...
Expand Down
2 changes: 1 addition & 1 deletion packages/plugin-vue/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@
"@jridgewell/gen-mapping": "^0.3.2",
"@jridgewell/trace-mapping": "^0.3.17",
"debug": "^4.3.4",
"rollup": "^2.79.1",
"rollup": "~3.2.3",
"slash": "^5.0.0",
"source-map": "^0.6.1",
"vite": "workspace:*",
Expand Down
2 changes: 1 addition & 1 deletion packages/vite/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@
"esbuild": "^0.15.9",
"postcss": "^8.4.18",
"resolve": "^1.22.1",
"rollup": "^2.79.1"
"rollup": "~3.2.3"
},
"optionalDependencies": {
"fsevents": "~2.3.2"
Expand Down
10 changes: 8 additions & 2 deletions packages/vite/rollup.config.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
/* eslint-disable no-restricted-globals */
import { readFileSync } from 'node:fs'
import path from 'node:path'
import { fileURLToPath } from 'node:url'
import nodeResolve from '@rollup/plugin-node-resolve'
import typescript from '@rollup/plugin-typescript'
import commonjs from '@rollup/plugin-commonjs'
Expand All @@ -8,7 +9,12 @@ import MagicString from 'magic-string'
import type { Plugin, RollupOptions } from 'rollup'
import { defineConfig } from 'rollup'
import licensePlugin from '../../scripts/rollupLicensePlugin.mjs'
import pkg from './package.json'

const pkg = JSON.parse(
readFileSync(new URL('./package.json', import.meta.url)).toString()
)

const __dirname = fileURLToPath(new URL('.', import.meta.url))

const envConfig = defineConfig({
input: path.resolve(__dirname, 'src/client/env.ts'),
Expand Down
24 changes: 15 additions & 9 deletions packages/vite/src/node/build.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ import { buildReporterPlugin } from './plugins/reporter'
import { buildEsbuildPlugin } from './plugins/esbuild'
import { terserPlugin } from './plugins/terser'
import {
asyncFlatten,
copyDir,
emptyDir,
joinUrlSegments,
Expand Down Expand Up @@ -383,25 +384,30 @@ export function resolveBuildOptions(
return resolved
}

export function resolveBuildPlugins(config: ResolvedConfig): {
export async function resolveBuildPlugins(config: ResolvedConfig): Promise<{
pre: Plugin[]
post: Plugin[]
} {
}> {
const options = config.build
const { commonjsOptions } = options
const usePluginCommonjs =
!Array.isArray(commonjsOptions?.include) ||
commonjsOptions?.include.length !== 0
const rollupOptionsPlugins = options.rollupOptions.plugins
return {
pre: [
completeSystemWrapPlugin(),
...(options.watch ? [ensureWatchPlugin()] : []),
watchPackageDataPlugin(config),
...(usePluginCommonjs ? [commonjsPlugin(options.commonjsOptions)] : []),
dataURIPlugin(),
...(options.rollupOptions.plugins
? (options.rollupOptions.plugins.filter(Boolean) as Plugin[])
: [])
...((
await asyncFlatten(
Array.isArray(rollupOptionsPlugins)
? rollupOptionsPlugins
: [rollupOptionsPlugins]
)
).filter(Boolean) as Plugin[])
],
post: [
buildImportAnalysisPlugin(config),
Expand Down Expand Up @@ -827,12 +833,12 @@ export function onRollupWarning(
config: ResolvedConfig
): void {
if (warning.code === 'UNRESOLVED_IMPORT') {
const id = warning.source
const importer = warning.importer
const id = warning.id
const exporter = warning.exporter
// throw unless it's commonjs external...
if (!importer || !/\?commonjs-external$/.test(importer)) {
if (!id || !/\?commonjs-external$/.test(id)) {
throw new Error(
`[vite]: Rollup failed to resolve import "${id}" from "${importer}".\n` +
`[vite]: Rollup failed to resolve import "${exporter}" from "${id}".\n` +
`This is most likely unintended because it can break your application at runtime.\n` +
`If you do want to externalize this module explicitly add it to\n` +
`\`build.rollupOptions.external\``
Expand Down
5 changes: 4 additions & 1 deletion packages/vite/src/node/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -569,7 +569,10 @@ export async function resolveConfig(
}))
}
return (
await container.resolveId(id, importer, { ssr, scan: options?.scan })
await container.resolveId(id, importer, {
ssr,
scan: options?.scan
})
)?.id
}
}
Expand Down
7 changes: 5 additions & 2 deletions packages/vite/src/node/constants.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
import path, { resolve } from 'node:path'
import { fileURLToPath } from 'node:url'
// @ts-expect-error
import { version } from '../../package.json'
import { readFileSync } from 'node:fs'

const { version } = JSON.parse(
readFileSync(new URL('../../package.json', import.meta.url)).toString()
)

export const VERSION = version as string

Expand Down
1 change: 1 addition & 0 deletions packages/vite/src/node/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -146,6 +146,7 @@ export interface Plugin extends RollupPlugin {
source: string,
importer: string | undefined,
options: {
assertions: Record<string, string>
custom?: CustomPluginOptions
ssr?: boolean
/**
Expand Down
3 changes: 1 addition & 2 deletions packages/vite/src/node/plugins/asset.ts
Original file line number Diff line number Diff line change
Expand Up @@ -494,8 +494,7 @@ async function fileToBuiltUrl(
name,
fileName: map.get(contentHash)!,
type: 'asset',
source: content,
isAsset: true
source: content
})
}

Expand Down
30 changes: 24 additions & 6 deletions packages/vite/src/node/plugins/css.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ import { CLIENT_PUBLIC_PATH, SPECIAL_QUERY_RE } from '../constants'
import type { ResolvedConfig } from '../config'
import type { Plugin } from '../plugin'
import {
arrayEqual,
asyncReplace,
cleanUrl,
combineSourcemaps,
Expand Down Expand Up @@ -305,7 +306,7 @@ export function cssPlugin(config: ResolvedConfig): Plugin {
export function cssPostPlugin(config: ResolvedConfig): Plugin {
// styles initialization in buildStart causes a styling loss in watch
const styles: Map<string, string> = new Map<string, string>()
let pureCssChunks: Set<string>
let pureCssChunks: Set<RenderedChunk>

// when there are multiple rollup outputs and extracting CSS, only emit once,
// since output formats have no effect on the generated CSS.
Expand Down Expand Up @@ -339,7 +340,7 @@ export function cssPostPlugin(config: ResolvedConfig): Plugin {

buildStart() {
// Ensure new caches for every build (i.e. rebuilding in watch mode)
pureCssChunks = new Set<string>()
pureCssChunks = new Set<RenderedChunk>()
outputToExtractedCSSMap = new Map<NormalizedOutputOptions, string>()
hasEmitted = false
},
Expand Down Expand Up @@ -537,7 +538,7 @@ export function cssPostPlugin(config: ResolvedConfig): Plugin {
if (config.build.cssCodeSplit) {
if (isPureCssChunk) {
// this is a shared CSS-only chunk that is empty.
pureCssChunks.add(chunk.fileName)
pureCssChunks.add(chunk)
}
if (opts.format === 'es' || opts.format === 'cjs') {
const cssAssetName = chunk.facadeModuleId
Expand Down Expand Up @@ -624,7 +625,24 @@ export function cssPostPlugin(config: ResolvedConfig): Plugin {

// remove empty css chunks and their imports
if (pureCssChunks.size) {
const emptyChunkFiles = [...pureCssChunks]
// map each pure css chunk (rendered chunk) to it's corresponding bundle
// chunk. we check that by comparing the `moduleIds` as they have different
// filenames (rendered chunk has the !~{XXX}~ placeholder)
const pureCssChunkNames: string[] = []
for (const pureCssChunk of pureCssChunks) {
for (const key in bundle) {
const bundleChunk = bundle[key]
if (
bundleChunk.type === 'chunk' &&
arrayEqual(bundleChunk.moduleIds, pureCssChunk.moduleIds)
) {
pureCssChunkNames.push(key)
break
}
}
}

const emptyChunkFiles = pureCssChunkNames
.map((file) => path.basename(file))
.join('|')
.replace(/\./g, '\\.')
Expand All @@ -641,7 +659,7 @@ export function cssPostPlugin(config: ResolvedConfig): Plugin {
// and also register the emitted CSS files under the importer
// chunks instead.
chunk.imports = chunk.imports.filter((file) => {
if (pureCssChunks.has(file)) {
if (pureCssChunkNames.includes(file)) {
const {
viteMetadata: { importedCss }
} = bundle[file] as OutputChunk
Expand All @@ -660,7 +678,7 @@ export function cssPostPlugin(config: ResolvedConfig): Plugin {
}
}
const removedPureCssFiles = removedPureCssFilesCache.get(config)!
pureCssChunks.forEach((fileName) => {
pureCssChunkNames.forEach((fileName) => {
removedPureCssFiles.set(fileName, bundle[fileName] as RenderedChunk)
delete bundle[fileName]
})
Expand Down
2 changes: 1 addition & 1 deletion packages/vite/src/node/plugins/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ export async function resolvePlugins(
const isBuild = config.command === 'build'
const isWatch = isBuild && !!config.build.watch
const buildPlugins = isBuild
? (await import('../build')).resolveBuildPlugins(config)
? await (await import('../build')).resolveBuildPlugins(config)
: { pre: [], post: [] }
const { modulePreload } = config.build

Expand Down
4 changes: 2 additions & 2 deletions packages/vite/src/node/plugins/splitVendorChunk.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import type {
GetManualChunk,
GetManualChunkApi,
GetModuleInfo,
ManualChunkMeta,
OutputOptions
} from 'rollup'
import type { UserConfig } from '../../node'
Expand Down Expand Up @@ -106,7 +106,7 @@ export function splitVendorChunkPlugin(): Plugin {
if (output.manualChunks) {
if (typeof output.manualChunks === 'function') {
const userManualChunks = output.manualChunks
output.manualChunks = (id: string, api: GetManualChunkApi) => {
output.manualChunks = (id: string, api: ManualChunkMeta) => {
return userManualChunks(id, api) ?? viteManualChunks(id, api)
}
}
Expand Down
4 changes: 4 additions & 0 deletions packages/vite/src/node/server/pluginContainer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,7 @@ export interface PluginContainer {
id: string,
importer?: string,
options?: {
assertions?: Record<string, string>
custom?: CustomPluginOptions
skip?: Set<Plugin>
ssr?: boolean
Expand Down Expand Up @@ -295,6 +296,7 @@ export async function createPluginContainer(
id: string,
importer?: string,
options?: {
assertions?: Record<string, string>
custom?: CustomPluginOptions
isEntry?: boolean
skipSelf?: boolean
Expand All @@ -306,6 +308,7 @@ export async function createPluginContainer(
skip.add(this._activePlugin)
}
let out = await container.resolveId(id, importer, {
assertions: options?.assertions,
custom: options?.custom,
isEntry: !!options?.isEntry,
skip,
Expand Down Expand Up @@ -587,6 +590,7 @@ export async function createPluginContainer(
? plugin.resolveId.handler
: plugin.resolveId
const result = await handler.call(ctx as any, rawId, importer, {
assertions: options?.assertions ?? {},
custom: options?.custom,
isEntry: !!options?.isEntry,
ssr,
Expand Down
9 changes: 9 additions & 0 deletions packages/vite/src/node/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1205,3 +1205,12 @@ export function joinUrlSegments(a: string, b: string): string {
}
return a + b
}

export function arrayEqual(a: any[], b: any[]): boolean {
if (a === b) return true
if (a.length !== b.length) return false
for (let i = 0; i < a.length; i++) {
if (a[i] !== b[i]) return false
}
return true
}
2 changes: 1 addition & 1 deletion playground/vitestSetup.ts
Original file line number Diff line number Diff line change
Expand Up @@ -306,7 +306,7 @@ export async function notifyRebuildComplete(
await new Promise<void>((resolve) => {
resolveFn = resolve
})
return watcher.removeListener('event', callback)
return watcher.off('event', callback)
}

function createInMemoryLogger(logs: string[]): Logger {
Expand Down
Loading

0 comments on commit beb7166

Please sign in to comment.