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

feat: support dev external #13215

Closed
wants to merge 12 commits into from
Closed
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
33 changes: 8 additions & 25 deletions packages/vite/src/node/build.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,13 @@ import { isDepsOptimizerEnabled, resolveConfig } from './config'
import { buildReporterPlugin } from './plugins/reporter'
import { buildEsbuildPlugin } from './plugins/esbuild'
import { terserPlugin } from './plugins/terser'
import { copyDir, emptyDir, lookupFile, normalizePath } from './utils'
import {
copyDir,
emptyDir,
lookupFile,
normalizePath,
resolveRollupExternal
} from './utils'
import { manifestPlugin } from './plugins/manifest'
import type { Logger } from './logger'
import { dataURIPlugin } from './plugins/dataUri'
Expand Down Expand Up @@ -749,34 +755,11 @@ async function cjsSsrResolveExternal(
return true
}
if (user) {
return resolveUserExternal(user, id, parentId, isResolved)
return resolveRollupExternal(user, id, parentId, isResolved)
}
}
}

function resolveUserExternal(
user: ExternalOption,
id: string,
parentId: string | undefined,
isResolved: boolean
) {
if (typeof user === 'function') {
return user(id, parentId, isResolved)
} else if (Array.isArray(user)) {
return user.some((test) => isExternal(id, test))
} else {
return isExternal(id, user)
}
}

function isExternal(id: string, test: string | RegExp) {
if (typeof test === 'string') {
return id === test
} else {
return test.test(id)
}
}

function injectSsrFlagToHooks(plugin: Plugin): Plugin {
const { resolveId, load, transform } = plugin
return {
Expand Down
11 changes: 8 additions & 3 deletions packages/vite/src/node/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -350,7 +350,8 @@ export type ResolveFn = (
id: string,
importer?: string,
aliasOnly?: boolean,
ssr?: boolean
ssr?: boolean,
ignoreExternal?: boolean
) => Promise<string | undefined>

export async function resolveConfig(
Expand Down Expand Up @@ -515,7 +516,7 @@ export async function resolveConfig(
const createResolver: ResolvedConfig['createResolver'] = (options) => {
let aliasContainer: PluginContainer | undefined
let resolverContainer: PluginContainer | undefined
return async (id, importer, aliasOnly, ssr) => {
return async (id, importer, aliasOnly, ssr, ignoreExternal) => {
let container: PluginContainer
if (aliasOnly) {
container =
Expand Down Expand Up @@ -546,7 +547,11 @@ export async function resolveConfig(
}))
}
return (
await container.resolveId(id, importer, { ssr, scan: options?.scan })
await container.resolveId(id, importer, {
ssr,
scan: options?.scan,
ignoreExternal
})
)?.id
}
}
Expand Down
2 changes: 1 addition & 1 deletion packages/vite/src/node/optimizer/esbuildDepPlugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ export function esbuildDepPlugin(
_importer = importer in qualified ? qualified[importer] : importer
}
const resolver = kind.startsWith('require') ? _resolveRequire : _resolve
return resolver(id, _importer, undefined, ssr)
return resolver(id, _importer, undefined, ssr, true)
}

const resolveResult = (id: string, resolved: string) => {
Expand Down
8 changes: 7 additions & 1 deletion packages/vite/src/node/plugins/importAnalysis.ts
Original file line number Diff line number Diff line change
Expand Up @@ -303,6 +303,10 @@ export function importAnalysisPlugin(config: ResolvedConfig): Plugin {
)
}

if (resolved.external) {
return [resolved.id, resolved.id]
}

const isRelative = url.startsWith('.')
const isSelfImport = !isRelative && cleanUrl(url) === cleanUrl(importer)

Expand Down Expand Up @@ -662,7 +666,9 @@ export function importAnalysisPlugin(config: ResolvedConfig): Plugin {
await Promise.all(
[...pluginImports].map((id) => normalizeUrl(id, 0))
)
).forEach(([url]) => importedUrls.add(url))
).forEach((normalized) => {
importedUrls.add(normalized[0])
})
}
// HMR transforms are no-ops in SSR, so an `accept` call will
// never be injected. Avoid updating the `isSelfAccepting`
Expand Down
95 changes: 66 additions & 29 deletions packages/vite/src/node/server/pluginContainer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ SOFTWARE.
*/

import fs from 'node:fs'
import { join, resolve } from 'node:path'
import path, { join, resolve } from 'node:path'
import { performance } from 'node:perf_hooks'
import { createRequire } from 'node:module'
import type {
Expand Down Expand Up @@ -69,6 +69,7 @@ import {
normalizePath,
numberToPos,
prettifyUrl,
resolveRollupExternal,
timeFrom
} from '../utils'
import { FS_PREFIX } from '../constants'
Expand Down Expand Up @@ -97,6 +98,10 @@ export interface PluginContainer {
* @internal
*/
scan?: boolean
/**
* @internal
*/
ignoreExternal?: boolean
isEntry?: boolean
}
): Promise<PartialResolvedId | null>
Expand Down Expand Up @@ -505,7 +510,22 @@ export async function createPluginContainer(
return {
acorn,
acornInjectPlugins: [],
...options
...options,
// normalize external as function
external(
id: string,
parentId: string | undefined,
isResolved: boolean
) {
if (options.external && !id.startsWith('\0')) {
return resolveRollupExternal(
options.external,
id,
parentId,
isResolved
)
}
}
}
})(),

Expand All @@ -528,46 +548,63 @@ export async function createPluginContainer(
const skip = options?.skip
const ssr = options?.ssr
const scan = !!options?.scan
const ignoreExternal = !!options?.ignoreExternal
const isEntry = !!options?.isEntry
const ctx = new Context()
ctx.ssr = !!ssr
ctx._scan = scan
ctx._resolveSkips = skip
const { external } = container.options as NormalizedInputOptions
const resolveStart = isDebug ? performance.now() : 0

let id: string | null = null
const partial: Partial<PartialResolvedId> = {}
for (const plugin of plugins) {
if (!plugin.resolveId) continue
if (skip?.has(plugin)) continue

ctx._activePlugin = plugin
if (!ignoreExternal && external(rawId, importer, false)) {
id = rawId
partial.external = true
} else {
for (const plugin of plugins) {
if (!plugin.resolveId) continue
if (skip?.has(plugin)) continue

ctx._activePlugin = plugin

const pluginResolveStart = isDebug ? performance.now() : 0
const result = await plugin.resolveId.call(
ctx as any,
rawId,
importer,
{ ssr, scan, isEntry }
)
if (!result) continue

const pluginResolveStart = isDebug ? performance.now() : 0
const result = await plugin.resolveId.call(
ctx as any,
rawId,
importer,
{ ssr, scan, isEntry }
)
if (!result) continue
if (typeof result === 'string') {
id = result
} else {
id = result.id
Object.assign(partial, result)
}

if (typeof result === 'string') {
id = result
} else {
id = result.id
Object.assign(partial, result)
}
isDebug &&
debugPluginResolve(
timeFrom(pluginResolveStart),
plugin.name,
prettifyUrl(id, root)
)

isDebug &&
debugPluginResolve(
timeFrom(pluginResolveStart),
plugin.name,
prettifyUrl(id, root)
)
// resolveId() is hookFirst - first non-null result is returned.
break
}

// resolveId() is hookFirst - first non-null result is returned.
break
if (
!ignoreExternal &&
!partial.external &&
external(id ?? rawId, importer, true)
) {
id ??= rawId
partial.external = true
}
}

if (isDebug && rawId !== id && !rawId.startsWith(FS_PREFIX)) {
Expand All @@ -577,7 +614,7 @@ export async function createPluginContainer(
seenResolves[key] = true
debugResolve(
`${timeFrom(resolveStart)} ${colors.cyan(rawId)} -> ${colors.dim(
id
partial.external ? '(external)' : id
)}`
)
}
Expand Down
25 changes: 24 additions & 1 deletion packages/vite/src/node/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ import debug from 'debug'
import type { Alias, AliasOptions } from 'types/alias'
import type MagicString from 'magic-string'

import type { TransformResult } from 'rollup'
import type { ExternalOption, TransformResult } from 'rollup'
import { createFilter as _createFilter } from '@rollup/pluginutils'
import {
CLIENT_ENTRY,
Expand Down Expand Up @@ -1087,3 +1087,26 @@ export const isNonDriveRelativeAbsolutePath = (p: string): boolean => {
if (!isWindows) return p.startsWith('/')
return windowsDrivePathPrefixRE.test(p)
}

export function resolveRollupExternal(
external: ExternalOption,
id: string,
parentId: string | undefined,
isResolved: boolean
): boolean | null | void {
if (typeof external === 'function') {
return external(id, parentId, isResolved)
} else if (Array.isArray(external)) {
return external.some((test) => isExternal(id, test))
} else {
return isExternal(id, external)
}
}

function isExternal(id: string, test: string | RegExp) {
if (typeof test === 'string') {
return id === test
} else {
return test.test(id)
}
}
5 changes: 5 additions & 0 deletions playground/external/__tests__/external.spec.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
import { describe, test } from 'vitest'
import { isBuild, page } from '~utils'

test('external', async () => {
expect(await page.textContent('#source-vue-version')).toBe('3.2.0')
})

describe.runIf(isBuild)('build', () => {
test('should externalize imported packages', async () => {
// If `vue` is successfully externalized, the page should use the version from the import map
Expand Down
1 change: 1 addition & 0 deletions playground/external/external-dep/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export const hello = 'world'
5 changes: 5 additions & 0 deletions playground/external/external-dep/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"name": "external-dep",
"version": "0.0.0",
"private": true
}
1 change: 1 addition & 0 deletions playground/external/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
<body>
<p>Imported Vue version: <span id="imported-vue-version"></span></p>
<p>Required Vue version: <span id="required-vue-version"></span></p>
<p>Source Vue version: <span id="source-vue-version"></span></p>
<script type="module" src="/src/main.js"></script>
</body>
</html>
3 changes: 2 additions & 1 deletion playground/external/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,8 @@
},
"dependencies": {
"@vitejs/dep-that-imports-vue": "file:./dep-that-imports-vue",
"@vitejs/dep-that-requires-vue": "file:./dep-that-requires-vue"
"@vitejs/dep-that-requires-vue": "file:./dep-that-requires-vue",
"external-dep": "file:./external-dep"
},
"devDependencies": {
"vite": "workspace:*",
Expand Down
7 changes: 7 additions & 0 deletions playground/external/src/main.js
Original file line number Diff line number Diff line change
@@ -1,2 +1,9 @@
import { version } from 'vue'
import '@vitejs/dep-that-imports-vue'
import '@vitejs/dep-that-requires-vue'

text('#source-vue-version', version)

function text(el, text) {
document.querySelector(el).textContent = text
}
11 changes: 11 additions & 0 deletions pnpm-lock.yaml

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