diff --git a/packages/vite/src/node/plugins/resolve.ts b/packages/vite/src/node/plugins/resolve.ts index 0a9a85374..8f07e1086 100644 --- a/packages/vite/src/node/plugins/resolve.ts +++ b/packages/vite/src/node/plugins/resolve.ts @@ -407,7 +407,9 @@ export function resolvePlugin(resolveOptions: InternalResolveOptions): Plugin { this.error(message) } - return options.idOnly ? id : { id, external: true } + return options.idOnly + ? id + : { id, external: true, moduleSideEffects: false } } else { if (!asSrc) { debug?.( diff --git a/playground/ssr-resolve/__tests__/ssr-resolve.spec.ts b/playground/ssr-resolve/__tests__/ssr-resolve.spec.ts index f3842838c..3920d4ccb 100644 --- a/playground/ssr-resolve/__tests__/ssr-resolve.spec.ts +++ b/playground/ssr-resolve/__tests__/ssr-resolve.spec.ts @@ -25,3 +25,11 @@ test.runIf(isBuild)('correctly resolve entrypoints', async () => { await expect(import(`${testDir}/dist/main.mjs`)).resolves.toBeTruthy() }) + +test.runIf(isBuild)( + 'node builtins should not be bundled if not used', + async () => { + const contents = readFile('dist/main.mjs') + expect(contents).not.include(`node:url`) + }, +) diff --git a/playground/ssr-resolve/main.js b/playground/ssr-resolve/main.js index 2357458b5..699ca5800 100644 --- a/playground/ssr-resolve/main.js +++ b/playground/ssr-resolve/main.js @@ -6,6 +6,7 @@ import fileEntry from '@vitejs/test-entries/file' import pkgExportsEntry from '@vitejs/test-resolve-pkg-exports/entry' import deepFoo from '@vitejs/test-deep-import/foo' import deepBar from '@vitejs/test-deep-import/bar' +import { used } from './util' export default ` entries/dir: ${dirEntry} @@ -13,4 +14,5 @@ export default ` pkg-exports/entry: ${pkgExportsEntry} deep-import/foo: ${deepFoo} deep-import/bar: ${deepBar} + util: ${used(['[success]'])} ` diff --git a/playground/ssr-resolve/util.js b/playground/ssr-resolve/util.js new file mode 100644 index 000000000..c3234a470 --- /dev/null +++ b/playground/ssr-resolve/util.js @@ -0,0 +1,10 @@ +import { pathToFileURL } from 'node:url' + +export function used(s) { + return s +} + +// This is not used, so `node:url` should not be bundled +export function treeshaken(s) { + return pathToFileURL(s) +}