Skip to content

Commit

Permalink
fix: read the correct package.json in ssrExternal (#5927)
Browse files Browse the repository at this point in the history
Fixes #5890
  • Loading branch information
benmccann authored Dec 2, 2021
1 parent 5b8c58b commit 7edabb4
Showing 1 changed file with 24 additions and 9 deletions.
33 changes: 24 additions & 9 deletions packages/vite/src/node/ssr/ssrExternal.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import {
normalizePath,
resolveFrom
} from '../utils'
import { ResolvedConfig } from '..'
import { Logger, ResolvedConfig } from '..'
import { createFilter } from '@rollup/pluginutils'

const debug = createDebugger('vite:ssr-external')
Expand Down Expand Up @@ -37,7 +37,8 @@ export function resolveSSRExternal(
config.root,
config.resolve.preserveSymlinks,
ssrExternals,
seen
seen,
config.logger
)

const importedDeps = knownImports.map(getNpmPackageName).filter(isDefined)
Expand Down Expand Up @@ -68,17 +69,18 @@ function collectExternals(
root: string,
preserveSymlinks: boolean | undefined,
ssrExternals: Set<string>,
seen: Set<string>
seen: Set<string>,
logger: Logger
) {
const pkgContent = lookupFile(root, ['package.json'])
if (!pkgContent) {
const rootPkgContent = lookupFile(root, ['package.json'])
if (!rootPkgContent) {
return
}

const pkg = JSON.parse(pkgContent)
const rootPkg = JSON.parse(rootPkgContent)
const deps = {
...pkg.devDependencies,
...pkg.dependencies
...rootPkg.devDependencies,
...rootPkg.dependencies
}

const resolveOptions: InternalResolveOptions = {
Expand Down Expand Up @@ -141,6 +143,14 @@ function collectExternals(
// or are there others like SystemJS / AMD that we'd need to handle?
// for now, we'll just leave this as is
else if (/\.m?js$/.test(esmEntry)) {
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' || esmEntry.endsWith('.mjs')) {
ssrExternals.add(id)
continue
Expand All @@ -149,12 +159,17 @@ function collectExternals(
const content = fs.readFileSync(esmEntry, 'utf-8')
if (/\bmodule\.exports\b|\bexports[.\[]|\brequire\s*\(/.test(content)) {
ssrExternals.add(id)
continue
}

logger.warn(
`${id} is incorrectly packaged. Please contact the package author to fix.`
)
}
}

for (const depRoot of depsToTrace) {
collectExternals(depRoot, preserveSymlinks, ssrExternals, seen)
collectExternals(depRoot, preserveSymlinks, ssrExternals, seen, logger)
}
}

Expand Down

0 comments on commit 7edabb4

Please sign in to comment.