Skip to content
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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
112 changes: 112 additions & 0 deletions packages/vite/src/node/__tests__/packages.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
import fs from 'node:fs'
import os from 'node:os'
import path from 'node:path'
import { afterEach, expect, test } from 'vitest'
import { findNearestMainPackageData } from '../packages'

let tempDir: string | undefined

afterEach(() => {
if (tempDir) fs.rmSync(tempDir, { recursive: true, force: true })
tempDir = undefined
})

function createFixtures(files: Record<string, object | string>): string {
tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'vite-packages-'))
for (const [file, content] of Object.entries(files)) {
const target = path.join(tempDir, file)
fs.mkdirSync(path.dirname(target), { recursive: true })
fs.writeFileSync(
target,
typeof content === 'string' ? content : JSON.stringify(content),
)
}
return tempDir
}

const projectManifest = { name: 'project' }

// paths after realpath resolution under pnpm:
// `<root>/node_modules/.pnpm/dep@1.0.0/node_modules/dep/...`
test('resolves the package root for the pnpm store layout', () => {
const root = createFixtures({
'package.json': projectManifest,
'node_modules/.pnpm/dep@1.0.0/node_modules/dep/package.json': {
name: 'dep',
version: '1.0.0',
license: 'MIT',
},
// nested type-marker manifest with a `name` but no `version`
'node_modules/.pnpm/dep@1.0.0/node_modules/dep/build/esm/package.json': {
name: 'dep',
type: 'module',
},
})
const pkg = findNearestMainPackageData(
path.join(root, 'node_modules/.pnpm/dep@1.0.0/node_modules/dep/build/esm'),
)
expect(pkg?.data).toMatchObject({ name: 'dep', version: '1.0.0' })
})

// packages hoisted by pnpm to `node_modules/.pnpm/node_modules/<pkg>`
test('resolves the package root for packages hoisted by pnpm', () => {
const root = createFixtures({
'package.json': projectManifest,
'node_modules/.pnpm/node_modules/hoisted/package.json': {
name: 'hoisted',
version: '1.0.0',
},
'node_modules/.pnpm/node_modules/hoisted/build/esm/package.json': {
name: 'hoisted',
type: 'module',
},
})
const pkg = findNearestMainPackageData(
path.join(root, 'node_modules/.pnpm/node_modules/hoisted/build/esm'),
)
expect(pkg?.data).toMatchObject({ name: 'hoisted', version: '1.0.0' })
})

test('resolves the package root for scoped packages', () => {
const root = createFixtures({
'package.json': projectManifest,
'node_modules/@scope/dep/package.json': {
name: '@scope/dep',
version: '2.0.0',
},
'node_modules/@scope/dep/dist/esm/package.json': {
name: '@scope/dep',
type: 'module',
},
})
const pkg = findNearestMainPackageData(
path.join(root, 'node_modules/@scope/dep/dist/esm'),
)
expect(pkg?.data).toMatchObject({ name: '@scope/dep', version: '2.0.0' })
})

// under Yarn PnP, packages are hosted inside zip archives at
// `.../cache/<pkg>-npm-<ver>-<hash>.zip/node_modules/<pkg>/...` (the cache
// may live outside the project, e.g. in `~/.yarn/berry/cache`). The path
// contains a synthesized `node_modules/<pkg>` segment, so the layout-based
// resolution covers PnP without any PnP-specific handling
test('resolves the package root for the Yarn PnP zip layout', () => {
const root = createFixtures({
'package.json': projectManifest,
'cache/engine.io-client-npm-6.6.6-fd14f4b531-10c0.zip/node_modules/engine.io-client/package.json':
{ name: 'engine.io-client', version: '6.6.6', license: 'MIT' },
// nested type-marker manifest with a `name` but no `version`
'cache/engine.io-client-npm-6.6.6-fd14f4b531-10c0.zip/node_modules/engine.io-client/build/esm/package.json':
{ name: 'engine.io-client', type: 'module' },
})
const pkg = findNearestMainPackageData(
path.join(
root,
'cache/engine.io-client-npm-6.6.6-fd14f4b531-10c0.zip/node_modules/engine.io-client/build/esm',
),
)
expect(pkg?.data).toMatchObject({
name: 'engine.io-client',
version: '6.6.6',
})
})
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,12 @@ exports[`json 1`] = `
"identifier": "MIT",
"text": "MIT License\\n\\nCopyright (c) ..."
},
{
"name": "@vitejs/test-dep-license-type-marker",
"version": "1.0.0",
"identifier": "MIT",
"text": "MIT License\\n\\nCopyright (c) ..."
},
{
"name": "@vitejs/test-dep-nested-license-isc",
"version": "0.0.0",
Expand All @@ -40,6 +46,12 @@ MIT License

Copyright (c) ...

## @vitejs/test-dep-license-type-marker - 1.0.0 (MIT)

MIT License

Copyright (c) ...

## @vitejs/test-dep-nested-license-isc - 0.0.0 (ISC)

Copyright (c) ...
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
// Avoid to be inlined completely: https://github.com/rolldown/rolldown/issues/8100
console.log()

export default 'devtools'
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"name": "@vitejs/test-dep-license-type-marker-devtools",
"version": "1.0.0",
"private": true,
"main": "index.js"
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
// Avoid to be inlined completely: https://github.com/rolldown/rolldown/issues/8100
console.log()

export { default as devtools } from '../devtools/index.js'
export default 'ok'
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
{
"name": "@vitejs/test-dep-license-type-marker",
"type": "module"
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
MIT License

Copyright (c) ...
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"name": "@vitejs/test-dep-license-type-marker",
"private": true,
"version": "1.0.0",
"license": "MIT",
"exports": {
".": "./build/esm/index.js"
}
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
<script type="module">
import dep1 from '@vitejs/test-dep-licence-cc0'
import dep2 from '@vitejs/test-dep-license-mit'
console.log(dep1, dep2)
import dep3 from '@vitejs/test-dep-license-type-marker'
console.log(dep1, dep2, dep3)
</script>
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
"type": "module",
"dependencies": {
"@vitejs/test-dep-license-mit": "file:./dep-license-mit",
"@vitejs/test-dep-license-type-marker": "file:./dep-license-type-marker",
"@vitejs/test-dep-licence-cc0": "file:./dep-licence-cc0"
}
}
38 changes: 29 additions & 9 deletions packages/vite/src/node/packages.ts
Original file line number Diff line number Diff line change
Expand Up @@ -158,20 +158,40 @@ export function findNearestPackageData(
return null
}

// Finds the nearest package.json with a `name` field
function isNodeModulesPackageRoot(pkgDir: string): boolean {
const parent = path.dirname(pkgDir)
if (path.basename(parent) === 'node_modules') {
return !path.basename(pkgDir).startsWith('@')
}
// scoped package root: `node_modules/@scope/pkg`
return (
path.basename(parent).startsWith('@') &&
path.basename(path.dirname(parent)) === 'node_modules'
)
}

// Finds the nearest package.json with a `name` field. For paths inside
// `node_modules`, the manifest at the package root is returned instead, which
// may be further up than the nearest manifest.
export function findNearestMainPackageData(
basedir: string,
packageCache?: PackageCache,
): PackageData | null {
const nearestPackage = findNearestPackageData(basedir, packageCache)
return (
nearestPackage &&
(nearestPackage.data.name
? nearestPackage
: findNearestMainPackageData(
path.dirname(nearestPackage.dir),
packageCache,
))
if (!nearestPackage) return null
if (
isInNodeModules(nearestPackage.dir) &&
!isNodeModulesPackageRoot(nearestPackage.dir)
) {
return findNearestMainPackageData(
path.dirname(nearestPackage.dir),
packageCache,
)
}
if (nearestPackage.data.name) return nearestPackage
return findNearestMainPackageData(
path.dirname(nearestPackage.dir),
packageCache,
)
}

Expand Down
32 changes: 21 additions & 11 deletions packages/vite/src/node/plugins/html.ts
Original file line number Diff line number Diff line change
Expand Up @@ -168,8 +168,24 @@ const noInlineLinkRels = new Set([
'apple-touch-icon',
'apple-touch-startup-image',
'manifest',
'modulepreload',
'preload',
'prefetch',
])

// If the node is a link, check if it can be inlined. If not, return `false` to
// force no inline. `undefined` leaves it to the default heuristics.
function getLinkShouldInline(
node: DefaultTreeAdapterMap['element'],
attributes: Record<string, string>,
): false | undefined {
const isNoInlineLink =
node.nodeName === 'link' &&
attributes.rel &&
parseRelAttr(attributes.rel).some((v) => noInlineLinkRels.has(v))
return isNoInlineLink ? false : undefined
}

export const isAsyncScriptMap: WeakMap<
ResolvedConfig,
Map<string, boolean>
Expand Down Expand Up @@ -636,7 +652,10 @@ export function buildHtmlPlugin(config: ResolvedConfig): Plugin {
decodedUrl !== undefined &&
!isExcludedUrl(decodedUrl)
) {
const result = await processAssetUrl(url)
const result = await processAssetUrl(
url,
getLinkShouldInline(node, attr.attributes),
)
return result !== decodedUrl
? encodeURIPath(result)
: url
Expand Down Expand Up @@ -675,20 +694,11 @@ export function buildHtmlPlugin(config: ResolvedConfig): Plugin {
})
js += importExpression
} else {
// If the node is a link, check if it can be inlined. If not, set `shouldInline`
// to `false` to force no inline. If `undefined`, it leaves to the default heuristics.
const isNoInlineLink =
node.nodeName === 'link' &&
attr.attributes.rel &&
parseRelAttr(attr.attributes.rel).some((v) =>
noInlineLinkRels.has(v),
)
const shouldInline = isNoInlineLink ? false : undefined
assetUrlsPromises.push(
(async () => {
const processedUrl = await processAssetUrl(
url,
shouldInline,
getLinkShouldInline(node, attr.attributes),
)
if (processedUrl !== url) {
overwriteAttrValue(
Expand Down
30 changes: 30 additions & 0 deletions playground/assets/__tests__/assets.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -328,6 +328,36 @@ describe('css url() references', () => {
expect(await getBg('.css-url-quotes-base64-inline')).toMatch(match)
})

test('no base64 inline for modulepreload links', async () => {
const el = await page.$(`link[rel="modulepreload"]`)
const href = await el.getAttribute('href')
expect(href).toMatch(
isBundled
? /\/foo\/bar\/assets\/preload-module-[-\w]{8}\.js/
: 'preload-module.js',
)
})

test('no base64 inline for preload and prefetch links', async () => {
const preloadAssetMatch = isBundled
? /\/foo\/bar\/assets\/preload-asset-[-\w]{8}\.png/
: '/foo/bar/nested/preload-asset.png'

const preloadEl = await page.$('link.preload-href')
expect(await preloadEl.getAttribute('href')).toMatch(preloadAssetMatch)

const prefetchEl = await page.$('link.prefetch-href')
expect(await prefetchEl.getAttribute('href')).toMatch(preloadAssetMatch)

// `imagesrcset` goes through the srcset branch, which has to honour the
// same no-inline decision as `href`
const imageSrcSetEl = await page.$('link.preload-imagesrcset')
const imageSrcSet = await imageSrcSetEl.getAttribute('imagesrcset')
imageSrcSet.split(', ').forEach((s) => {
expect(s).toMatch(preloadAssetMatch)
})
})

test('no base64 inline for icon and manifest links', async () => {
const iconEl = await page.$(`link.ico`)
const href = await iconEl.getAttribute('href')
Expand Down
18 changes: 18 additions & 0 deletions playground/assets/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,24 @@
<meta charset="UTF-8" />
<link class="ico" rel="icon" type="image/svg+xml" href="favicon.ico" />
<link rel="manifest" href="manifest.json" />
<link rel="modulepreload" href="preload-module.js" />
<link
class="preload-href"
rel="preload"
as="image"
href="./nested/preload-asset.png"
/>
<link
class="preload-imagesrcset"
rel="preload"
as="image"
imagesrcset="./nested/preload-asset.png 1x, ./nested/preload-asset.png 2x"
/>
<link
class="prefetch-href"
rel="prefetch"
href="./nested/preload-asset.png"
/>
<meta
class="meta-og-image"
property="og:image"
Expand Down
Binary file added playground/assets/nested/preload-asset.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
2 changes: 2 additions & 0 deletions playground/assets/preload-module.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
// referenced via <link rel="modulepreload">, small enough to hit assetsInlineLimit
export const preloadedModule = 'preloaded'
Loading
Loading