Unverified Commit f7048b55 authored by Tobias Koppers's avatar Tobias Koppers Committed by GitHub

fix external fallback for invalid packages (#30427)

fallback to alternative external version also when it fails because of base resolve mismatch#

fix resolved .mjs modules treated as external

fixes #30330
parent 46ddd8cf
...@@ -741,34 +741,96 @@ export default async function getBaseWebpackConfig( ...@@ -741,34 +741,96 @@ export default async function getBaseWebpackConfig(
// When in esm externals mode, and using import, we resolve with // When in esm externals mode, and using import, we resolve with
// ESM resolving options. // ESM resolving options.
const isEsmRequested = dependencyType === 'esm' const isEsmRequested = dependencyType === 'esm'
const preferEsm = esmExternals && isEsmRequested
const resolve = getResolve( let res: string | null = null
preferEsm ? NODE_ESM_RESOLVE_OPTIONS : NODE_RESOLVE_OPTIONS
)
// Resolve the import with the webpack provided context, this
// ensures we're resolving the correct version when multiple
// exist.
let res: string | null
let isEsm: boolean = false let isEsm: boolean = false
try {
;[res, isEsm] = await resolve(context, request)
} catch (err) {
res = null
}
// If resolving fails, and we can use an alternative way let preferEsmOptions =
// try the alternative resolving options. esmExternals && isEsmRequested ? [true, false] : [false]
if (!res && (isEsmRequested || looseEsmExternals)) { for (const preferEsm of preferEsmOptions) {
const resolveAlternative = getResolve( const resolve = getResolve(
preferEsm ? NODE_RESOLVE_OPTIONS : NODE_ESM_RESOLVE_OPTIONS preferEsm ? NODE_ESM_RESOLVE_OPTIONS : NODE_RESOLVE_OPTIONS
) )
// Resolve the import with the webpack provided context, this
// ensures we're resolving the correct version when multiple
// exist.
try {
;[res, isEsm] = await resolve(context, request)
} catch (err) {
res = null
}
console.log(`${request} = ${res} ${preferEsm}`)
if (!res) {
continue
}
// ESM externals can only be imported (and not required).
// Make an exception in loose mode.
if (!isEsmRequested && isEsm && !looseEsmExternals) {
continue
}
if (isLocal) {
// Makes sure dist/shared and dist/server are not bundled
// we need to process shared `router/router` and `dynamic`,
// so that the DefinePlugin can inject process.env values
const isNextExternal =
/next[/\\]dist[/\\](shared|server)[/\\](?!lib[/\\](router[/\\]router|dynamic))/.test(
res
)
if (isNextExternal) {
// Generate Next.js external import
const externalRequest = path.posix.join(
'next',
'dist',
path
.relative(
// Root of Next.js package:
path.join(__dirname, '..'),
res
)
// Windows path normalization
.replace(/\\/g, '/')
)
return `commonjs ${externalRequest}`
} else {
// We don't want to retry local requests
// with other preferEsm options
return
}
}
// Bundled Node.js code is relocated without its node_modules tree.
// This means we need to make sure its request resolves to the same
// package that'll be available at runtime. If it's not identical,
// we need to bundle the code (even if it _should_ be external).
let baseRes: string | null
let baseIsEsm: boolean
try { try {
;[res, isEsm] = await resolveAlternative(context, request) const baseResolve = getResolve(
isEsm ? NODE_BASE_ESM_RESOLVE_OPTIONS : NODE_BASE_RESOLVE_OPTIONS
)
;[baseRes, baseIsEsm] = await baseResolve(dir, request)
} catch (err) { } catch (err) {
baseRes = null
baseIsEsm = false
}
// Same as above: if the package, when required from the root,
// would be different from what the real resolution would use, we
// cannot externalize it.
// if request is pointing to a symlink it could point to the the same file,
// the resolver will resolve symlinks so this is handled
if (baseRes !== res || isEsm !== baseIsEsm) {
res = null res = null
continue
} }
break
} }
// If the request cannot be resolved we need to have // If the request cannot be resolved we need to have
...@@ -785,60 +847,6 @@ export default async function getBaseWebpackConfig( ...@@ -785,60 +847,6 @@ export default async function getBaseWebpackConfig(
) )
} }
if (isLocal) {
// Makes sure dist/shared and dist/server are not bundled
// we need to process shared `router/router` and `dynamic`,
// so that the DefinePlugin can inject process.env values
const isNextExternal =
/next[/\\]dist[/\\](shared|server)[/\\](?!lib[/\\](router[/\\]router|dynamic))/.test(
res
)
if (isNextExternal) {
// Generate Next.js external import
const externalRequest = path.posix.join(
'next',
'dist',
path
.relative(
// Root of Next.js package:
path.join(__dirname, '..'),
res
)
// Windows path normalization
.replace(/\\/g, '/')
)
return `commonjs ${externalRequest}`
} else {
return
}
}
// Bundled Node.js code is relocated without its node_modules tree.
// This means we need to make sure its request resolves to the same
// package that'll be available at runtime. If it's not identical,
// we need to bundle the code (even if it _should_ be external).
let baseRes: string | null
let baseIsEsm: boolean
try {
const baseResolve = getResolve(
isEsm ? NODE_BASE_ESM_RESOLVE_OPTIONS : NODE_BASE_RESOLVE_OPTIONS
)
;[baseRes, baseIsEsm] = await baseResolve(dir, request)
} catch (err) {
baseRes = null
baseIsEsm = false
}
// Same as above: if the package, when required from the root,
// would be different from what the real resolution would use, we
// cannot externalize it.
// if request is pointing to a symlink it could point to the the same file,
// the resolver will resolve symlinks so this is handled
if (baseRes !== res || isEsm !== baseIsEsm) {
return
}
const externalType = isEsm ? 'module' : 'commonjs' const externalType = isEsm ? 'module' : 'commonjs'
if ( if (
...@@ -866,11 +874,13 @@ export default async function getBaseWebpackConfig( ...@@ -866,11 +874,13 @@ export default async function getBaseWebpackConfig(
// Anything else that is standard JavaScript within `node_modules` // Anything else that is standard JavaScript within `node_modules`
// can be externalized. // can be externalized.
if (/node_modules[/\\].*\.c?js$/.test(res)) { if (/node_modules[/\\].*\.[mc]?js$/.test(res)) {
console.log(`${externalType} ${request} = ${res}`)
return `${externalType} ${request}` return `${externalType} ${request}`
} }
// Default behavior: bundle the code! // Default behavior: bundle the code!
console.log(`bundle ${res}`)
} }
const emacsLockfilePattern = '**/.#*' const emacsLockfilePattern = '**/.#*'
......
module.exports = { module.exports = {
experimental: {
esmExternals: true,
},
webpack(config, { isServer }) { webpack(config, { isServer }) {
config.resolve.alias = { config.resolve.alias = {
...config.resolve.alias, ...config.resolve.alias,
......
export default "World"; export default "World";
// ensure it's external
if(!process.browser && Math.random() < 0) import("fail");
\ No newline at end of file
export default 'World' export default 'World'
// ensure it's external
if (!process.browser && Math.random() < 0) import('fail')
module.exports = 'World'
// ensure it's external
if (!process.browser && Math.random() < 0) require('fail')
{
"name": "invalid-esm-package",
"exports": {
"./entry": {
"import": "./wrong.js",
"require": "./correct.js"
}
}
}
import React from 'preact/compat' import React from 'preact/compat'
import World1 from 'esm-package1/entry' import World1 from 'esm-package1/entry'
import World2 from 'esm-package2/entry' import World2 from 'esm-package2/entry'
import World3 from 'invalid-esm-package/entry'
export async function getStaticProps() { export async function getStaticProps() {
return { return {
props: {}, props: {
worlds: `${World1}+${World2}+${World3}`,
},
} }
} }
export default function Index(props) { export default function Index({ worlds }) {
return ( return (
<div> <div>
Hello {World1}+{World2} Hello {World1}+{World2}+{World3}+{worlds}
</div> </div>
) )
} }
import React from 'preact/compat' import React from 'preact/compat'
import World1 from 'esm-package1/entry' import World1 from 'esm-package1/entry'
import World2 from 'esm-package2/entry' import World2 from 'esm-package2/entry'
import World3 from 'invalid-esm-package/entry'
export function getServerSideProps() { export function getServerSideProps() {
return {} return {
props: {
worlds: `${World1}+${World2}+${World3}`,
},
}
} }
export default function Index(props) { export default function Index({ worlds }) {
return ( return (
<div> <div>
Hello {World1}+{World2} Hello {World1}+{World2}+{World3}+{worlds}
</div> </div>
) )
} }
import React from 'preact/compat' import React from 'preact/compat'
import World1 from 'esm-package1/entry' import World1 from 'esm-package1/entry'
import World2 from 'esm-package2/entry' import World2 from 'esm-package2/entry'
import World3 from 'invalid-esm-package/entry'
export default function Index(props) { const worlds = 'World+World+World'
export default function Index() {
return ( return (
<div> <div>
Hello {World1}+{World2} Hello {World1}+{World2}+{World3}+{worlds}
</div> </div>
) )
} }
...@@ -23,7 +23,8 @@ describe('Handle ESM externals with esmExternals: true', () => { ...@@ -23,7 +23,8 @@ describe('Handle ESM externals with esmExternals: true', () => {
}) })
afterAll(() => killApp(app)) afterAll(() => killApp(app))
const expected = /Hello <!-- -->World<!-- -->\+<!-- -->World/ const expected =
/Hello <!-- -->World<!-- -->\+<!-- -->World<!-- -->\+<!-- -->World<!-- -->\+<!-- -->World\+World\+World/
it('should render the static page', async () => { it('should render the static page', async () => {
const html = await renderViaHTTP(appPort, '/static') const html = await renderViaHTTP(appPort, '/static')
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment