Skip to content

Commit

Permalink
Refactor app dir related flags (vercel#41166)
Browse files Browse the repository at this point in the history
simplify the `appDir` passing down
  • Loading branch information
huozhi authored and BowlingX committed Oct 5, 2022
1 parent 8c18687 commit 19fbbeb
Show file tree
Hide file tree
Showing 29 changed files with 132 additions and 93 deletions.
2 changes: 1 addition & 1 deletion packages/next-plugin-storybook/preset.js
Expand Up @@ -6,8 +6,8 @@ const getWebpackConfig = require('next/dist/build/webpack-config').default
const CWD = process.cwd()

async function webpackFinal(config) {
const pagesDir = findPagesDir(CWD)
const nextConfig = await loadConfig(PHASE_PRODUCTION_BUILD, CWD)
const pagesDir = findPagesDir(CWD, !!nextConfig.experimental.appDir)
const nextWebpackConfig = await getWebpackConfig(CWD, {
pagesDir,
entrypoints: {},
Expand Down
8 changes: 4 additions & 4 deletions packages/next/build/entries.ts
Expand Up @@ -164,7 +164,7 @@ export function getEdgeServerEntry(opts: {
page: string
pages: { [page: string]: string }
middleware?: Partial<MiddlewareConfig>
pagesType?: 'app' | 'pages' | 'root'
pagesType: 'app' | 'pages' | 'root'
appDirLoader?: string
}) {
if (isMiddlewareFile(opts.page)) {
Expand Down Expand Up @@ -526,13 +526,13 @@ export function finalizeEntrypoint({
compilerType,
value,
isServerComponent,
appDir,
hasAppDir,
}: {
compilerType?: CompilerNameValues
name: string
value: ObjectValue<webpack.EntryObject>
isServerComponent?: boolean
appDir?: boolean
hasAppDir?: boolean
}): ObjectValue<webpack.EntryObject> {
const entry =
typeof value !== 'object' || Array.isArray(value)
Expand Down Expand Up @@ -575,7 +575,7 @@ export function finalizeEntrypoint({
name !== CLIENT_STATIC_FILES_RUNTIME_REACT_REFRESH
) {
// TODO-APP: this is a temporary fix. @shuding is going to change the handling of server components
if (appDir && entry.import.includes('flight')) {
if (hasAppDir && entry.import.includes('flight')) {
return {
dependOn: CLIENT_STATIC_FILES_RUNTIME_MAIN_APP,
...entry,
Expand Down
10 changes: 4 additions & 6 deletions packages/next/build/index.ts
Expand Up @@ -301,10 +301,8 @@ export default async function build(
setGlobal('telemetry', telemetry)

const publicDir = path.join(dir, 'public')
const { pages: pagesDir, appDir } = findPagesDir(
dir,
config.experimental.appDir
)
const hasAppDir = !!config.experimental.appDir
const { pagesDir, appDir } = findPagesDir(dir, hasAppDir)

const hasPublicDir = await fileExists(publicDir)

Expand Down Expand Up @@ -396,7 +394,7 @@ export default async function build(
config.experimental.cpus,
config.experimental.workerThreads,
telemetry,
!!config.experimental.appDir
hasAppDir
)
}),
])
Expand Down Expand Up @@ -1990,7 +1988,7 @@ export default async function build(
combinedPages.length > 0 ||
useStatic404 ||
useDefaultStatic500 ||
config.experimental.appDir
hasAppDir
) {
const staticGenerationSpan =
nextBuildSpan.traceChild('static-generation')
Expand Down
7 changes: 6 additions & 1 deletion packages/next/build/jest/jest.ts
Expand Up @@ -64,14 +64,18 @@ export default function nextJest(options: { dir?: string } = {}) {
let resolvedBaseUrl
let isEsmProject = false
let pagesDir: string | undefined
let hasServerComponents: boolean | undefined

if (options.dir) {
const resolvedDir = resolve(options.dir)
pagesDir = findPagesDir(resolvedDir).pages
const packageConfig = loadClosestPackageJson(resolvedDir)
isEsmProject = packageConfig.type === 'module'

nextConfig = await getConfig(resolvedDir)
const hasAppDir = !!nextConfig.experimental.appDir
const findPagesDirResult = findPagesDir(resolvedDir, hasAppDir)
hasServerComponents = !!findPagesDirResult.appDir
pagesDir = findPagesDirResult.pagesDir
setUpEnv(resolvedDir, nextConfig)
// TODO: revisit when bug in SWC is fixed that strips `.css`
const result = await loadJsConfig(resolvedDir, nextConfig)
Expand Down Expand Up @@ -134,6 +138,7 @@ export default function nextJest(options: { dir?: string } = {}) {
nextConfig,
jsConfig,
resolvedBaseUrl,
hasServerComponents,
isEsmProject,
pagesDir,
},
Expand Down
1 change: 1 addition & 0 deletions packages/next/build/swc/jest-transformer.js
Expand Up @@ -48,6 +48,7 @@ module.exports = {
jsConfig: inputOptions.jsConfig,
resolvedBaseUrl: inputOptions.resolvedBaseUrl,
pagesDir: inputOptions.pagesDir,
hasServerComponents: inputOptions.hasServerComponents,
esm:
isSupportEsm &&
isEsm(Boolean(inputOptions.isEsmProject), filename, jestConfig),
Expand Down
7 changes: 6 additions & 1 deletion packages/next/build/swc/options.js
Expand Up @@ -34,6 +34,7 @@ function getBaseSWCOptions({
swcCacheDir,
isServerLayer,
relativeFilePathFromRoot,
hasServerComponents,
}) {
const parserConfig = getParserOptions({ filename, jsConfig })
const paths = jsConfig?.compilerOptions?.paths
Expand Down Expand Up @@ -119,7 +120,7 @@ function getBaseSWCOptions({
modularizeImports: nextConfig?.experimental?.modularizeImports,
relay: nextConfig?.compiler?.relay,
emotion: getEmotionOptions(nextConfig, development),
serverComponents: nextConfig?.experimental?.appDir
serverComponents: hasServerComponents
? {
isServer: !!isServerLayer,
}
Expand Down Expand Up @@ -180,6 +181,7 @@ export function getJestSWCOptions({
nextConfig,
jsConfig,
pagesDir,
hasServerComponents,
// This is not passed yet as "paths" resolving needs a test first
// resolvedBaseUrl,
}) {
Expand All @@ -191,6 +193,7 @@ export function getJestSWCOptions({
globalWindow: !isServer,
nextConfig,
jsConfig,
hasServerComponents,
// resolvedBaseUrl,
})

Expand Down Expand Up @@ -226,6 +229,7 @@ export function getLoaderSWCOptions({
supportedBrowsers,
swcCacheDir,
relativeFilePathFromRoot,
hasServerComponents,
// This is not passed yet as "paths" resolving is handled by webpack currently.
// resolvedBaseUrl,
}) {
Expand All @@ -240,6 +244,7 @@ export function getLoaderSWCOptions({
swcCacheDir,
isServerLayer,
relativeFilePathFromRoot,
hasServerComponents,
})

const isNextDist = nextDistPath.test(filename)
Expand Down
33 changes: 18 additions & 15 deletions packages/next/build/webpack-config.ts
Expand Up @@ -33,9 +33,9 @@ import { execOnce } from '../shared/lib/utils'
import { NextConfigComplete } from '../server/config-shared'
import { finalizeEntrypoint } from './entries'
import * as Log from './output/log'
import { build as buildConfiguration } from './webpack/config'
import { buildConfiguration } from './webpack/config'
import MiddlewarePlugin, {
handleWebpackExtenalForEdgeRuntime,
handleWebpackExternalForEdgeRuntime,
} from './webpack/plugins/middleware-plugin'
import BuildManifestPlugin from './webpack/plugins/build-manifest-plugin'
import { JsConfigPathsPlugin } from './webpack/plugins/jsconfig-paths-plugin'
Expand Down Expand Up @@ -563,6 +563,10 @@ export default async function getBaseWebpackConfig(
rewrites.afterFiles.length > 0 ||
rewrites.fallback.length > 0

const hasAppDir = !!config.experimental.appDir
const hasConcurrentFeatures = hasReactRoot
const hasServerComponents = hasAppDir

// Only error in first one compiler (client) once
if (isClient) {
if (!hasReactRoot) {
Expand All @@ -571,16 +575,14 @@ export default async function getBaseWebpackConfig(
'`experimental.runtime` requires React 18 to be installed.'
)
}
if (config.experimental.appDir) {
if (hasAppDir) {
throw new Error(
'`experimental.appDir` requires React 18 to be installed.'
)
}
}
}

const hasConcurrentFeatures = hasReactRoot
const hasServerComponents = !!config.experimental.appDir
const disableOptimizedLoading = hasConcurrentFeatures
? true
: config.experimental.disableOptimizedLoading
Expand Down Expand Up @@ -654,6 +656,7 @@ export default async function getBaseWebpackConfig(
pagesDir,
cwd: dir,
development: dev,
hasServerComponents,
hasReactRefresh: dev && isClient,
hasJsxRuntime: true,
},
Expand Down Expand Up @@ -682,6 +685,7 @@ export default async function getBaseWebpackConfig(
isServer: isNodeServer || isEdgeServer,
rootDir: dir,
pagesDir,
hasServerComponents,
hasReactRefresh: dev && isClient,
fileReading: config.experimental.swcFileReading,
nextConfig: config,
Expand Down Expand Up @@ -745,7 +749,7 @@ export default async function getBaseWebpackConfig(
)
)
.replace(/\\/g, '/'),
...(config.experimental.appDir
...(hasAppDir
? {
[CLIENT_STATIC_FILES_RUNTIME_MAIN_APP]: dev
? [
Expand Down Expand Up @@ -1215,7 +1219,7 @@ export default async function getBaseWebpackConfig(
'{}',
'react-dom': '{}',
},
handleWebpackExtenalForEdgeRuntime,
handleWebpackExternalForEdgeRuntime,
]
: []),
]
Expand Down Expand Up @@ -1520,7 +1524,7 @@ export default async function getBaseWebpackConfig(
},
module: {
rules: [
...(config.experimental.appDir && !isClient && !isEdgeServer
...(hasAppDir && !isClient && !isEdgeServer
? [
{
issuerLayer: WEBPACK_LAYERS.server,
Expand Down Expand Up @@ -1827,7 +1831,7 @@ export default async function getBaseWebpackConfig(
appDir: dir,
esmExternals: config.experimental.esmExternals,
outputFileTracingRoot: config.experimental.outputFileTracingRoot,
appDirEnabled: !!config.experimental.appDir,
appDirEnabled: hasAppDir,
}
),
// Moment.js is an extremely popular library that bundles large locale files
Expand Down Expand Up @@ -1872,7 +1876,7 @@ export default async function getBaseWebpackConfig(
serverless: isLikeServerless,
dev,
isEdgeRuntime: isEdgeServer,
appDirEnabled: !!config.experimental.appDir,
appDirEnabled: hasAppDir,
}),
// MiddlewarePlugin should be after DefinePlugin so NEXT_PUBLIC_*
// replacement is done before its process.env.* handling
Expand All @@ -1888,7 +1892,7 @@ export default async function getBaseWebpackConfig(
rewrites,
isDevFallback,
exportRuntime: hasConcurrentFeatures,
appDirEnabled: !!config.experimental.appDir,
appDirEnabled: hasAppDir,
}),
new ProfilingPlugin({ runWebpackSpan }),
config.optimizeFonts &&
Expand Down Expand Up @@ -1919,9 +1923,7 @@ export default async function getBaseWebpackConfig(
minimized: true,
},
}),
!!config.experimental.appDir &&
isClient &&
new AppBuildManifestPlugin({ dev }),
hasAppDir && isClient && new AppBuildManifestPlugin({ dev }),
hasServerComponents &&
(isClient
? new FlightManifestPlugin({
Expand Down Expand Up @@ -2200,6 +2202,7 @@ export default async function getBaseWebpackConfig(
customAppFile: pagesDir
? new RegExp(escapeStringRegexp(path.join(pagesDir, `_app`)))
: undefined,
hasAppDir,
isDevelopment: dev,
isServer: isNodeServer || isEdgeServer,
isEdgeRuntime: isEdgeServer,
Expand Down Expand Up @@ -2588,7 +2591,7 @@ export default async function getBaseWebpackConfig(
value: entry[name],
compilerType,
name,
appDir: config.experimental.appDir,
hasAppDir,
})
}

Expand Down
12 changes: 6 additions & 6 deletions packages/next/build/webpack/config/blocks/css/index.ts
Expand Up @@ -257,7 +257,7 @@ export const css = curry(async function css(

// CSS Modules support must be enabled on the server and client so the class
// names are available for SSR or Prerendering.
if (ctx.experimental.appDir && !ctx.isProduction) {
if (ctx.hasAppDir && !ctx.isProduction) {
fns.push(
loader({
oneOf: [
Expand Down Expand Up @@ -373,7 +373,7 @@ export const css = curry(async function css(
)
}

if (!ctx.experimental.appDir) {
if (!ctx.hasAppDir) {
// Throw an error for CSS Modules used outside their supported scope
fns.push(
loader({
Expand All @@ -393,7 +393,7 @@ export const css = curry(async function css(
}

if (ctx.isServer) {
if (ctx.experimental.appDir && !ctx.isProduction) {
if (ctx.hasAppDir && !ctx.isProduction) {
fns.push(
loader({
oneOf: [
Expand All @@ -420,7 +420,7 @@ export const css = curry(async function css(
)
}
} else {
if (ctx.experimental.appDir) {
if (ctx.hasAppDir) {
fns.push(
loader({
oneOf: [
Expand Down Expand Up @@ -552,7 +552,7 @@ export const css = curry(async function css(
oneOf: [
markRemovable({
test: [regexCssGlobal, regexSassGlobal],
issuer: ctx.experimental.appDir
issuer: ctx.hasAppDir
? {
// If it's inside the app dir, but not importing from a layout file,
// throw an error.
Expand Down Expand Up @@ -597,7 +597,7 @@ export const css = curry(async function css(
}

// Enable full mini-css-extract-plugin hmr for prod mode pages or app dir
if (ctx.isClient && (ctx.isProduction || ctx.experimental.appDir)) {
if (ctx.isClient && (ctx.isProduction || ctx.hasAppDir)) {
// Extract CSS as CSS file(s) in the client-side production bundle.
const MiniCssExtractPlugin =
require('../../../plugins/mini-css-extract-plugin').default
Expand Down
@@ -1,16 +1,16 @@
import type { webpack } from 'next/dist/compiled/webpack/webpack'

export function getClientStyleLoader({
isAppDir,
hasAppDir,
isDevelopment,
assetPrefix,
}: {
isAppDir: boolean
hasAppDir: boolean
isDevelopment: boolean
assetPrefix: string
}): webpack.RuleSetUseItem {
// Keep next-style-loader for development mode in `pages/`
if (isDevelopment && !isAppDir) {
if (isDevelopment && !hasAppDir) {
return {
loader: 'next-style-loader',
options: {
Expand Down
Expand Up @@ -15,7 +15,7 @@ export function getFontLoader(
// loader
loaders.push(
getClientStyleLoader({
isAppDir: !!ctx.experimental.appDir,
hasAppDir: ctx.hasAppDir,
isDevelopment: ctx.isDevelopment,
assetPrefix: ctx.assetPrefix,
})
Expand Down
Expand Up @@ -16,7 +16,7 @@ export function getGlobalCssLoader(
// loader
loaders.push(
getClientStyleLoader({
isAppDir: !!ctx.experimental.appDir,
hasAppDir: ctx.hasAppDir,
isDevelopment: ctx.isDevelopment,
assetPrefix: ctx.assetPrefix,
})
Expand Down
Expand Up @@ -16,7 +16,7 @@ export function getCssModuleLoader(
// loader
loaders.push(
getClientStyleLoader({
isAppDir: !!ctx.experimental.appDir,
hasAppDir: ctx.hasAppDir,
isDevelopment: ctx.isDevelopment,
assetPrefix: ctx.assetPrefix,
})
Expand Down

0 comments on commit 19fbbeb

Please sign in to comment.