Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: use simpler resolve for nested optimized deps #12770

Merged
merged 1 commit into from
Apr 6, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
1 change: 0 additions & 1 deletion packages/vite/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,6 @@
"dependencies": {
"esbuild": "^0.17.5",
"postcss": "^8.4.21",
"resolve": "^1.22.1",
"rollup": "^3.20.2"
},
"optionalDependencies": {
Expand Down
7 changes: 7 additions & 0 deletions packages/vite/rollup.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,13 @@ function createNodePlugins(
pattern: /^var json = typeof JSON.+require\('jsonify'\);$/gm,
replacement: 'var json = JSON',
},
// postcss-import uses the `resolve` dep if the `resolve` option is not passed.
// However, we always pass the `resolve` option. Remove this import to avoid
// bundling the `resolve` dep.
'postcss-import/index.js': {
src: 'const resolveId = require("./lib/resolve-id")',
replacement: 'const resolveId = undefined',
},
}),

commonjs({
Expand Down
2 changes: 2 additions & 0 deletions packages/vite/src/node/plugins/preAlias.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,8 @@ export function preAliasPlugin(config: ResolvedConfig): Plugin {
depsOptimizer,
id,
importer,
config.resolve.preserveSymlinks,
config.packageCache,
)
if (optimizedId) {
return optimizedId // aliased dep already optimized
Expand Down
45 changes: 26 additions & 19 deletions packages/vite/src/node/plugins/resolve.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,6 @@ import {
isTsRequest,
isWindows,
normalizePath,
resolveFrom,
safeRealpathSync,
slash,
tryStatSync,
Expand Down Expand Up @@ -318,7 +317,13 @@ export function resolvePlugin(resolveOptions: InternalResolveOptions): Plugin {
asSrc &&
depsOptimizer &&
!options.scan &&
(res = await tryOptimizedResolve(depsOptimizer, id, importer))
(res = await tryOptimizedResolve(
depsOptimizer,
id,
importer,
options.preserveSymlinks,
options.packageCache,
))
) {
return res
}
Expand Down Expand Up @@ -854,6 +859,8 @@ export async function tryOptimizedResolve(
depsOptimizer: DepsOptimizer,
id: string,
importer?: string,
preserveSymlinks?: boolean,
packageCache?: PackageCache,
): Promise<string | undefined> {
// TODO: we need to wait until scanning is done here as this function
// is used in the preAliasPlugin to decide if an aliased dep is optimized,
Expand All @@ -871,31 +878,31 @@ export async function tryOptimizedResolve(
if (!importer) return

// further check if id is imported by nested dependency
let resolvedSrc: string | undefined
let idPkgDir: string | undefined
const nestedIdMatch = `> ${id}`

for (const optimizedData of metadata.depInfoList) {
if (!optimizedData.src) continue // Ignore chunks

const pkgPath = optimizedData.id
// check for scenarios, e.g.
// pkgPath => "my-lib > foo"
// id => "foo"
// this narrows the need to do a full resolve
if (!pkgPath.endsWith(id)) continue
// check where "foo" is nested in "my-lib > foo"
if (!optimizedData.id.endsWith(nestedIdMatch)) continue

// lazily initialize resolvedSrc
if (resolvedSrc == null) {
try {
// this may throw errors if unable to resolve, e.g. aliased id
resolvedSrc = normalizePath(resolveFrom(id, path.dirname(importer)))
} catch {
// this is best-effort only so swallow errors
break
}
// lazily initialize idPkgDir
if (idPkgDir == null) {
idPkgDir = resolvePackageData(
id,
importer,
preserveSymlinks,
packageCache,
)?.dir
// if still null, it likely means that this id isn't a dep for importer.
// break to bail early
if (idPkgDir == null) break
idPkgDir = normalizePath(idPkgDir)
}

// match by src to correctly identify if id belongs to nested dependency
if (optimizedData.src === resolvedSrc) {
if (optimizedData.src.startsWith(idPkgDir)) {
return depsOptimizer.getOptimizedDepId(optimizedData)
}
}
Expand Down
19 changes: 0 additions & 19 deletions packages/vite/src/node/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ import { builtinModules, createRequire } from 'node:module'
import { promises as dns } from 'node:dns'
import { performance } from 'node:perf_hooks'
import type { AddressInfo, Server } from 'node:net'
import resolve from 'resolve'
import type { FSWatcher } from 'chokidar'
import remapping from '@ampproject/remapping'
import type { DecodedSourceMap, RawSourceMap } from '@ampproject/remapping'
Expand All @@ -22,7 +21,6 @@ import { createFilter as _createFilter } from '@rollup/pluginutils'
import {
CLIENT_ENTRY,
CLIENT_PUBLIC_PATH,
DEFAULT_EXTENSIONS,
ENV_PUBLIC_PATH,
FS_PREFIX,
NULL_BYTE_PLACEHOLDER,
Expand Down Expand Up @@ -145,23 +143,6 @@ export const deepImportRE = /^([^@][^/]*)\/|^(@[^/]+\/[^/]+)\//
// TODO: use import()
const _require = createRequire(import.meta.url)

const ssrExtensions = ['.js', '.cjs', '.json', '.node']

export function resolveFrom(
id: string,
basedir: string,
preserveSymlinks = false,
ssr = false,
): string {
return resolve.sync(id, {
basedir,
paths: [],
extensions: ssr ? ssrExtensions : DEFAULT_EXTENSIONS,
// necessary to work with pnpm
preserveSymlinks: preserveSymlinks || !!process.versions.pnp || false,
})
}

// set in bin/vite.js
const filter = process.env.VITE_DEBUG_FILTER

Expand Down
2 changes: 0 additions & 2 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.