Skip to content

Commit

Permalink
fix: lower .mjs resolve priority
Browse files Browse the repository at this point in the history
close #1660
  • Loading branch information
yyx990803 committed Jan 23, 2021
1 parent 2f7ecaf commit b15e90e
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 8 deletions.
3 changes: 2 additions & 1 deletion packages/vite/src/node/optimizer/index.ts
Expand Up @@ -250,11 +250,12 @@ export async function optimizeDeps(

await init
for (const output in meta.outputs) {
if (/chunk\.\w+\.js$/.test(output)) continue
const absolute = normalizePath(path.resolve(output))
const relative = normalizePath(path.relative(cacheDir, absolute))
for (const id in qualified) {
const entry = qualified[id]
if (entry.endsWith(relative)) {
if (entry.replace(/\.mjs$/, '.js').endsWith(relative)) {
// check if this is a cjs dep.
const [imports, exports] = parse(fs.readFileSync(entry, 'utf-8'))
data.optimized[id] = {
Expand Down
17 changes: 10 additions & 7 deletions packages/vite/src/node/plugins/resolve.ts
Expand Up @@ -25,11 +25,10 @@ import { PartialResolvedId } from 'rollup'
import { isCSSRequest } from './css'
import { resolve as _resolveExports } from 'resolve.exports'

const mainFields = [
const altMainFields = [
'module',
'jsnext:main', // moment still uses this...
'jsnext',
'main'
'jsnext'
]

function resolveExports(
Expand Down Expand Up @@ -455,7 +454,11 @@ export function resolvePackageEntry(
entryPoint = resolveExports(data, '.', isProduction)
}

if (!entryPoint) {
// if exports resolved to .mjs, still resolve other fields.
// This is because .mjs files can technically import .cjs files which would
// make them invalid for pure ESM environments - so if other module/browser
// fields are present, prioritize those instead.
if (!entryPoint || entryPoint.endsWith('.mjs')) {
// check browser field
// https://github.com/defunctzombie/package-browser-field-spec
const browserEntry =
Expand Down Expand Up @@ -492,16 +495,16 @@ export function resolvePackageEntry(
}
}

if (!entryPoint) {
for (const field of mainFields) {
if (!entryPoint || entryPoint.endsWith('.mjs')) {
for (const field of altMainFields) {
if (typeof data[field] === 'string') {
entryPoint = data[field]
break
}
}
}

entryPoint = entryPoint || 'index.js'
entryPoint = entryPoint || data.main || 'index.js'

// resolve object browser field in package.json
const { browser: browserField } = data
Expand Down

0 comments on commit b15e90e

Please sign in to comment.