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

fix(ssr): prefer CJS but still allow ESM entries #5662

Merged
merged 6 commits into from
Nov 13, 2021
Merged
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
23 changes: 17 additions & 6 deletions packages/vite/src/node/ssr/ssrModuleLoader.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import {
import { transformRequest } from '../server/transformRequest'
import { InternalResolveOptions, tryNodeResolve } from '../plugins/resolve'
import { hookNodeResolve } from '../plugins/ssrRequireHook'
import { DEFAULT_MAIN_FIELDS } from '../constants'

interface SSRContext {
global: typeof globalThis
Expand Down Expand Up @@ -101,19 +102,29 @@ async function instantiateModule(
root
} = server.config

// The `extensions` and `mainFields` options are used to ensure that
// CommonJS modules are preferred. We want to avoid ESM->ESM imports
// whenever possible, because `hookNodeResolve` can't intercept them.
const resolveOptions: InternalResolveOptions = {
conditions: ['node'],
// By adding "require" to the `conditions` array, resolution of the
// pkg.exports field will use "require" condition whenever it comes
// before "import" condition.
conditions: ['node', 'require'],
dedupe,
// Prefer CommonJS modules.
extensions: ['.js', '.mjs', '.ts', '.jsx', '.tsx', '.json'],
extensions: ['.js', '.cjs', '.mjs', '.jsx', '.json'],
patak-dev marked this conversation as resolved.
Show resolved Hide resolved
isBuild: true,
isProduction,
// Disable "module" condition.
isRequire: true,
mainFields: ['main'],
mainFields: ['main', ...DEFAULT_MAIN_FIELDS],
root
}

// Prevent ESM modules from being resolved during test runs, since Jest
// cannot `require` them. Note: This prevents testing of ESM-only packages.
if (typeof jest !== 'undefined') {
resolveOptions.isRequire = true
resolveOptions.mainFields = ['main']
}

// Since dynamic imports can happen in parallel, we need to
// account for multiple pending deps and duplicate imports.
const pendingDeps: string[] = []
Expand Down