Unverified Commit 1c75bf78 authored by Kristoffer K's avatar Kristoffer K Committed by GitHub

perf(next): use require.resolve instead of resolve (#19518)

**What's the problem this PR addresses?**

- ~~https://github.com/vercel/next.js/pull/18768 started to ncc babel and thus it's version of resolve which breaks PnP support~~
Babel replaced `resolve` with the builtin `require.resolve` and a polyfill for older node versions in https://github.com/babel/babel/pull/12439 which was upgraded in https://github.com/vercel/next.js/pull/20586
- `next` unnecessarily bundles the `resolve` package when `require.resolve` is builtin and can do the same job

**How did you fix it?**

- ~~Avoid running `resolve` through ncc~~
Added a test for https://github.com/vercel/next.js/issues/19334 (closes https://github.com/vercel/next.js/issues/19334)
- Replace `resolve` with `require.resolve`
parent 4e3eb733
import findUp from 'next/dist/compiled/find-up' import findUp from 'next/dist/compiled/find-up'
import { promises } from 'fs' import { promises } from 'fs'
import path from 'path' import path from 'path'
import resolve from 'next/dist/compiled/resolve/index.js'
import { execOnce } from '../../next-server/lib/utils' import { execOnce } from '../../next-server/lib/utils'
const { version } = require('next/package.json') const { version } = require('next/package.json')
...@@ -213,10 +212,7 @@ async function _collectPlugins( ...@@ -213,10 +212,7 @@ async function _collectPlugins(
nextPluginNames.map((name) => nextPluginNames.map((name) =>
collectPluginMeta( collectPluginMeta(
env, env,
resolve.sync(path.join(name, 'package.json'), { require.resolve(path.join(name, 'package.json'), { paths: [dir] }),
basedir: dir,
preserveSymlinks: true,
}),
name, name,
version version
) )
......
...@@ -18,7 +18,6 @@ import { ...@@ -18,7 +18,6 @@ import {
import { fileExists } from '../lib/file-exists' import { fileExists } from '../lib/file-exists'
import { getPackageVersion } from '../lib/get-package-version' import { getPackageVersion } from '../lib/get-package-version'
import { Rewrite } from '../lib/load-custom-routes' import { Rewrite } from '../lib/load-custom-routes'
import { resolveRequest } from '../lib/resolve-request'
import { getTypeScriptConfiguration } from '../lib/typescript/getTypeScriptConfiguration' import { getTypeScriptConfiguration } from '../lib/typescript/getTypeScriptConfiguration'
import { import {
CLIENT_STATIC_FILES_RUNTIME_MAIN, CLIENT_STATIC_FILES_RUNTIME_MAIN,
...@@ -306,7 +305,7 @@ export default async function getBaseWebpackConfig( ...@@ -306,7 +305,7 @@ export default async function getBaseWebpackConfig(
let typeScriptPath: string | undefined let typeScriptPath: string | undefined
try { try {
typeScriptPath = resolveRequest('typescript', `${dir}/`) typeScriptPath = require.resolve('typescript', { paths: [dir] })
} catch (_) {} } catch (_) {}
const tsConfigPath = path.join(dir, 'tsconfig.json') const tsConfigPath = path.join(dir, 'tsconfig.json')
const useTypeScript = Boolean( const useTypeScript = Boolean(
...@@ -607,7 +606,7 @@ export default async function getBaseWebpackConfig( ...@@ -607,7 +606,7 @@ export default async function getBaseWebpackConfig(
// exist. // exist.
let res: string let res: string
try { try {
res = resolveRequest(request, `${context}/`) res = require.resolve(request, { paths: [context] })
} catch (err) { } catch (err) {
// If the request cannot be resolved, we need to tell webpack to // If the request cannot be resolved, we need to tell webpack to
// "bundle" it so that webpack shows an error (that it cannot be // "bundle" it so that webpack shows an error (that it cannot be
...@@ -645,7 +644,7 @@ export default async function getBaseWebpackConfig( ...@@ -645,7 +644,7 @@ export default async function getBaseWebpackConfig(
// we need to bundle the code (even if it _should_ be external). // we need to bundle the code (even if it _should_ be external).
let baseRes: string | null let baseRes: string | null
try { try {
baseRes = resolveRequest(request, `${dir}/`) baseRes = require.resolve(request, { paths: [dir] })
} catch (err) { } catch (err) {
baseRes = null baseRes = null
} }
...@@ -1420,11 +1419,11 @@ export default async function getBaseWebpackConfig( ...@@ -1420,11 +1419,11 @@ export default async function getBaseWebpackConfig(
try { try {
// Resolve the version of `@zeit/next-css` as depended on by the Sass, // Resolve the version of `@zeit/next-css` as depended on by the Sass,
// Less or Stylus plugin. // Less or Stylus plugin.
const correctNextCss = resolveRequest( const correctNextCss = require.resolve('@zeit/next-css', {
'@zeit/next-css', paths: [
isCss isCss
? // Resolve `@zeit/next-css` from the base directory ? // Resolve `@zeit/next-css` from the base directory
`${dir}/` dir
: // Else, resolve it from the specific plugins : // Else, resolve it from the specific plugins
require.resolve( require.resolve(
isSass isSass
...@@ -1434,15 +1433,18 @@ export default async function getBaseWebpackConfig( ...@@ -1434,15 +1433,18 @@ export default async function getBaseWebpackConfig(
: isStylus : isStylus
? '@zeit/next-stylus' ? '@zeit/next-stylus'
: 'next' : 'next'
) ),
) ],
})
// If we found `@zeit/next-css` ... // If we found `@zeit/next-css` ...
if (correctNextCss) { if (correctNextCss) {
// ... resolve the version of `css-loader` shipped with that // ... resolve the version of `css-loader` shipped with that
// package instead of whichever was hoisted highest in your // package instead of whichever was hoisted highest in your
// `node_modules` tree. // `node_modules` tree.
const correctCssLoader = resolveRequest(use.loader, correctNextCss) const correctCssLoader = require.resolve(use.loader, {
paths: [correctNextCss],
})
if (correctCssLoader) { if (correctCssLoader) {
// We saved the user from a failed build! // We saved the user from a failed build!
use.loader = correctCssLoader use.loader = correctCssLoader
......
import chalk from 'chalk' import chalk from 'chalk'
import { findConfig } from '../../../../../lib/find-config' import { findConfig } from '../../../../../lib/find-config'
import { resolveRequest } from '../../../../../lib/resolve-request'
import browserslist from 'browserslist' import browserslist from 'browserslist'
type CssPluginCollection_Array = (string | [string, boolean | object])[] type CssPluginCollection_Array = (string | [string, boolean | object])[]
...@@ -57,7 +56,7 @@ async function loadPlugin( ...@@ -57,7 +56,7 @@ async function loadPlugin(
throw new Error(genericErrorText) throw new Error(genericErrorText)
} }
const pluginPath = resolveRequest(pluginName, `${dir}/`) const pluginPath = require.resolve(pluginName, { paths: [dir] })
if (isIgnoredPlugin(pluginPath)) { if (isIgnoredPlugin(pluginPath)) {
return false return false
} else if (options === true) { } else if (options === true) {
......
This software is released under the MIT license:
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
This diff is collapsed.
{"name":"resolve","main":"index.js","author":{"name":"James Halliday","email":"mail@substack.net","url":"http://substack.net"},"license":"MIT"}
...@@ -2,7 +2,6 @@ import { promises as fs } from 'fs' ...@@ -2,7 +2,6 @@ import { promises as fs } from 'fs'
import findUp from 'next/dist/compiled/find-up' import findUp from 'next/dist/compiled/find-up'
import JSON5 from 'next/dist/compiled/json5' import JSON5 from 'next/dist/compiled/json5'
import * as path from 'path' import * as path from 'path'
import { resolveRequest } from './resolve-request'
type PackageJsonDependencies = { type PackageJsonDependencies = {
dependencies: Record<string, string> dependencies: Record<string, string>
...@@ -52,7 +51,9 @@ export async function getPackageVersion({ ...@@ -52,7 +51,9 @@ export async function getPackageVersion({
: `${cwd}/` : `${cwd}/`
try { try {
const targetPath = resolveRequest(`${name}/package.json`, cwd2) const targetPath = require.resolve(`${name}/package.json`, {
paths: [cwd2],
})
const targetContent = await fs.readFile(targetPath, 'utf-8') const targetContent = await fs.readFile(targetPath, 'utf-8')
return JSON5.parse(targetContent).version ?? null return JSON5.parse(targetContent).version ?? null
} catch { } catch {
......
import resolve from 'next/dist/compiled/resolve/index.js'
import path from 'path'
export function resolveRequest(req: string, issuer: string): string {
// The `resolve` package is prebuilt through ncc, which prevents
// PnP from being able to inject itself into it. To circumvent
// this, we simply use PnP directly when available.
if (process.versions.pnp) {
const { resolveRequest: pnpResolveRequest } = require(`pnpapi`)
return pnpResolveRequest(req, issuer, { considerBuiltins: false })
} else {
const basedir =
issuer.endsWith(path.posix.sep) || issuer.endsWith(path.win32.sep)
? issuer
: path.dirname(issuer)
return resolve.sync(req, { basedir })
}
}
...@@ -2,7 +2,6 @@ import chalk from 'chalk' ...@@ -2,7 +2,6 @@ import chalk from 'chalk'
import path from 'path' import path from 'path'
import { fileExists } from '../file-exists' import { fileExists } from '../file-exists'
import { getOxfordCommaList } from '../oxford-comma-list' import { getOxfordCommaList } from '../oxford-comma-list'
import { resolveRequest } from '../resolve-request'
import { FatalTypeScriptError } from './FatalTypeScriptError' import { FatalTypeScriptError } from './FatalTypeScriptError'
const requiredPackages = [ const requiredPackages = [
...@@ -22,7 +21,7 @@ export async function hasNecessaryDependencies( ...@@ -22,7 +21,7 @@ export async function hasNecessaryDependencies(
const missingPackages = requiredPackages.filter((p) => { const missingPackages = requiredPackages.filter((p) => {
try { try {
resolutions.set(p.pkg, resolveRequest(p.file, path.join(baseDir, '/'))) resolutions.set(p.pkg, require.resolve(p.file, { paths: [baseDir] }))
return false return false
} catch (_) { } catch (_) {
return true return true
......
...@@ -172,7 +172,6 @@ ...@@ -172,7 +172,6 @@
"@types/react": "16.9.17", "@types/react": "16.9.17",
"@types/react-dom": "16.9.4", "@types/react-dom": "16.9.4",
"@types/react-is": "16.7.1", "@types/react-is": "16.7.1",
"@types/resolve": "0.0.8",
"@types/semver": "7.3.1", "@types/semver": "7.3.1",
"@types/send": "0.14.4", "@types/send": "0.14.4",
"@types/sharp": "0.26.0", "@types/sharp": "0.26.0",
...@@ -220,7 +219,6 @@ ...@@ -220,7 +219,6 @@
"postcss-preset-env": "6.7.0", "postcss-preset-env": "6.7.0",
"postcss-scss": "3.0.4", "postcss-scss": "3.0.4",
"recast": "0.18.5", "recast": "0.18.5",
"resolve": "1.11.0",
"semver": "7.3.2", "semver": "7.3.2",
"send": "0.17.1", "send": "0.17.1",
"source-map": "0.6.1", "source-map": "0.6.1",
......
...@@ -404,16 +404,6 @@ export async function ncc_recast(task, opts) { ...@@ -404,16 +404,6 @@ export async function ncc_recast(task, opts) {
.target('compiled/recast') .target('compiled/recast')
} }
// eslint-disable-next-line camelcase // eslint-disable-next-line camelcase
// NB: Used by other dependencies, but Vercel version is a duplicate
// version so can be inlined anyway (although may change in future)
externals['resolve'] = 'next/dist/compiled/resolve'
export async function ncc_resolve(task, opts) {
await task
.source(opts.src || relative(__dirname, require.resolve('resolve')))
.ncc({ packageName: 'resolve', externals })
.target('compiled/resolve')
}
// eslint-disable-next-line camelcase
externals['schema-utils'] = 'next/dist/compiled/schema-utils' externals['schema-utils'] = 'next/dist/compiled/schema-utils'
export async function ncc_schema_utils(task, opts) { export async function ncc_schema_utils(task, opts) {
await task await task
...@@ -576,7 +566,6 @@ export async function ncc(task) { ...@@ -576,7 +566,6 @@ export async function ncc(task) {
'ncc_postcss_preset_env', 'ncc_postcss_preset_env',
'ncc_postcss_scss', 'ncc_postcss_scss',
'ncc_recast', 'ncc_recast',
'ncc_resolve',
'ncc_schema_utils', 'ncc_schema_utils',
'ncc_send', 'ncc_send',
'ncc_source_map', 'ncc_source_map',
......
...@@ -145,10 +145,6 @@ declare module 'next/dist/compiled/recast' { ...@@ -145,10 +145,6 @@ declare module 'next/dist/compiled/recast' {
import m from 'recast' import m from 'recast'
export = m export = m
} }
declare module 'next/dist/compiled/resolve/index.js' {
import m from 'resolve'
export = m
}
declare module 'next/dist/compiled/send' { declare module 'next/dist/compiled/send' {
import m from 'send' import m from 'send'
export = m export = m
......
declare -a testCases=( declare -a testCases=(
"with-typescript" "with-typescript"
"with-next-sass" "with-next-sass"
# Tests @next/mdx
"with-mdx" "with-mdx"
# Tests babel config
"with-styled-components"
) )
set -e set -e
...@@ -25,6 +28,7 @@ do ...@@ -25,6 +28,7 @@ do
touch yarn.lock touch yarn.lock
yarn set version berry yarn set version berry
yarn config set pnpFallbackMode none yarn config set pnpFallbackMode none
yarn config set enableGlobalCache true
yarn link --all --private -r ../.. yarn link --all --private -r ../..
yarn build yarn build
......
...@@ -2944,12 +2944,6 @@ ...@@ -2944,12 +2944,6 @@
"@types/prop-types" "*" "@types/prop-types" "*"
csstype "^2.2.0" csstype "^2.2.0"
"@types/resolve@0.0.8":
version "0.0.8"
resolved "https://registry.yarnpkg.com/@types/resolve/-/resolve-0.0.8.tgz#f26074d238e02659e323ce1a13d041eee280e194"
dependencies:
"@types/node" "*"
"@types/resolve@1.17.1": "@types/resolve@1.17.1":
version "1.17.1" version "1.17.1"
resolved "https://registry.yarnpkg.com/@types/resolve/-/resolve-1.17.1.tgz#3afd6ad8967c77e4376c598a82ddd58f46ec45d6" resolved "https://registry.yarnpkg.com/@types/resolve/-/resolve-1.17.1.tgz#3afd6ad8967c77e4376c598a82ddd58f46ec45d6"
...@@ -13655,13 +13649,6 @@ resolve@1.1.7: ...@@ -13655,13 +13649,6 @@ resolve@1.1.7:
version "1.1.7" version "1.1.7"
resolved "https://registry.yarnpkg.com/resolve/-/resolve-1.1.7.tgz#203114d82ad2c5ed9e8e0411b3932875e889e97b" resolved "https://registry.yarnpkg.com/resolve/-/resolve-1.1.7.tgz#203114d82ad2c5ed9e8e0411b3932875e889e97b"
resolve@1.11.0:
version "1.11.0"
resolved "https://registry.yarnpkg.com/resolve/-/resolve-1.11.0.tgz#4014870ba296176b86343d50b60f3b50609ce232"
integrity sha512-WL2pBDjqT6pGUNSUzMw00o4T7If+z4H2x3Gz893WoUQ5KW8Vr9txp00ykiP16VBaZF5+j/OcXJHZ9+PCvdiDKw==
dependencies:
path-parse "^1.0.6"
resolve@1.17.0: resolve@1.17.0:
version "1.17.0" version "1.17.0"
resolved "https://registry.yarnpkg.com/resolve/-/resolve-1.17.0.tgz#b25941b54968231cc2d1bb76a79cb7f2c0bf8444" resolved "https://registry.yarnpkg.com/resolve/-/resolve-1.17.0.tgz#b25941b54968231cc2d1bb76a79cb7f2c0bf8444"
......
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