diff --git a/packages/vite/src/node/ssr/ssrExternal.ts b/packages/vite/src/node/ssr/ssrExternal.ts index 5c04e78ac067eb..d81634a1a485ca 100644 --- a/packages/vite/src/node/ssr/ssrExternal.ts +++ b/packages/vite/src/node/ssr/ssrExternal.ts @@ -1,7 +1,14 @@ +import fs from 'fs' import path from 'path' import type { InternalResolveOptions } from '../plugins/resolve' import { tryNodeResolve } from '../plugins/resolve' -import { createDebugger, isDefined, lookupFile, resolveFrom } from '../utils' +import { + createDebugger, + isDefined, + lookupFile, + normalizePath, + resolveFrom +} from '../utils' import type { Logger, ResolvedConfig } from '..' import { createFilter } from '@rollup/pluginutils' @@ -105,6 +112,7 @@ function collectExternals( seen.add(id) let esmEntry: string | undefined + let requireEntry: string try { esmEntry = tryNodeResolve( id, @@ -114,6 +122,9 @@ function collectExternals( undefined, true )?.id + // normalizePath required for windows. tryNodeResolve uses normalizePath + // which returns with '/', require.resolve returns with '\\' + requireEntry = normalizePath(require.resolve(id, { paths: [root] })) } catch (e) { try { // no main entry, but deep imports may be allowed @@ -130,6 +141,29 @@ function collectExternals( debug(`Failed to resolve entries for package "${id}"\n`, e) continue } + + const pkgPath = resolveFrom(`${id}/package.json`, root) + const pkgContent = fs.readFileSync(pkgPath, 'utf-8') + + if (!pkgContent) { + continue + } + const pkg = JSON.parse(pkgContent) + + if (pkg.type === 'module') { + if (requireEntry && !requireEntry.endsWith('.cjs')) { + logger.warn( + `${id} must use a .cjs extension for the CJS entry point when "type": "module" is set. Please contact the package author to fix.` + ) + } + } else { + if (esmEntry && !esmEntry.endsWith('.mjs')) { + logger.warn( + `${id} must either set "type": "module" or use an .mjs extension for the ESM entry point. Please contact the package author to fix.` + ) + } + } + if (esmEntry && !esmEntry.includes('node_modules')) { // trace the dependencies of linked packages const pkgPath = resolveFrom(`${id}/package.json`, root)