Unverified Commit ccc8d271 authored by JJ Kasper's avatar JJ Kasper Committed by GitHub

Revert "edge-ssr: bundle next/dist as ESM for better tree-shaking (#40251) (#40967)

This reverts commit 11deaaa8.

Temporarily reverts the above commit due to breaking middleware/edge
functions once deployed.

Fixes:
https://github.com/vercel/next.js/actions/runs/3133433920/jobs/5087331787

cc @shuding @feedthejim 

```sh
[GET] /blog/first
13:56:56:61
2022-09-27T20:56:56.671Z	61d43a6a-34a1-40c0-b71f-4ae5d1918431	ERROR	/var/task/node_modules/next/dist/esm/client/router.js:1
/* global window */ import React from 'react';
                    ^^^^^^
SyntaxError: Cannot use import statement outside a module
    at Object.compileFunction (node:vm:352:18)
    at wrapSafe (node:internal/modules/cjs/loader:1033:15)
    at Module._compile (node:internal/modules/cjs/loader:1069:27)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1159:10)
    at Module.load (node:internal/modules/cjs/loader:981:32)
    at Function.Module._load (node:internal/modules/cjs/loader:822:12)
    at Module.require (node:internal/modules/cjs/loader:1005:19)
    at require (node:internal/modules/cjs/helpers:102:18)
    at Object.<anonymous> (/var/task/node_modules/next/router.js:3:7)
    at Module._compile (node:internal/modules/cjs/loader:1105:14)
```
parent b16fcccf
module.exports = module.exports = require('./dist/shared/lib/amp')
process.env.NEXT_RUNTIME === 'edge'
? require('./dist/esm/shared/lib/amp')
: require('./dist/shared/lib/amp')
module.exports = module.exports = require('./dist/pages/_app')
process.env.NEXT_RUNTIME === 'edge'
? require('./dist/esm/pages/_app')
: require('./dist/pages/_app')
...@@ -219,7 +219,6 @@ export function getAppEntry(opts: { ...@@ -219,7 +219,6 @@ export function getAppEntry(opts: {
appDir: string appDir: string
appPaths: string[] | null appPaths: string[] | null
pageExtensions: string[] pageExtensions: string[]
nextRuntime: string
}) { }) {
return { return {
import: `next-app-loader?${stringify(opts)}!`, import: `next-app-loader?${stringify(opts)}!`,
...@@ -456,7 +455,6 @@ export async function createEntrypoints(params: CreateEntrypointsParams) { ...@@ -456,7 +455,6 @@ export async function createEntrypoints(params: CreateEntrypointsParams) {
appDir, appDir,
appPaths: matchedAppPaths, appPaths: matchedAppPaths,
pageExtensions, pageExtensions,
nextRuntime: 'nodejs',
}) })
} else if (isTargetLikeServerless(target)) { } else if (isTargetLikeServerless(target)) {
if (page !== '/_app' && page !== '/_document') { if (page !== '/_app' && page !== '/_document') {
...@@ -481,7 +479,6 @@ export async function createEntrypoints(params: CreateEntrypointsParams) { ...@@ -481,7 +479,6 @@ export async function createEntrypoints(params: CreateEntrypointsParams) {
appDir: appDir!, appDir: appDir!,
appPaths: matchedAppPaths, appPaths: matchedAppPaths,
pageExtensions, pageExtensions,
nextRuntime: 'edge',
}).import }).import
} }
......
...@@ -180,9 +180,11 @@ export function getDefineEnv({ ...@@ -180,9 +180,11 @@ export function getDefineEnv({
}), }),
// TODO: enforce `NODE_ENV` on `process.env`, and add a test: // TODO: enforce `NODE_ENV` on `process.env`, and add a test:
'process.env.NODE_ENV': JSON.stringify(dev ? 'development' : 'production'), 'process.env.NODE_ENV': JSON.stringify(dev ? 'development' : 'production'),
'process.env.NEXT_RUNTIME': JSON.stringify( ...((isNodeServer || isEdgeServer) && {
isEdgeServer ? 'edge' : isNodeServer ? 'nodejs' : undefined 'process.env.NEXT_RUNTIME': JSON.stringify(
), isEdgeServer ? 'edge' : 'nodejs'
),
}),
'process.env.__NEXT_MIDDLEWARE_MATCHERS': JSON.stringify( 'process.env.__NEXT_MIDDLEWARE_MATCHERS': JSON.stringify(
middlewareMatchers || [] middlewareMatchers || []
), ),
...@@ -793,7 +795,7 @@ export default async function getBaseWebpackConfig( ...@@ -793,7 +795,7 @@ export default async function getBaseWebpackConfig(
return prev return prev
}, [] as string[]) }, [] as string[])
: []), : []),
isEdgeServer ? 'next/dist/esm/pages/_app.js' : 'next/dist/pages/_app.js', 'next/dist/pages/_app.js',
] ]
customAppAliases[`${PAGES_DIR_ALIAS}/_error`] = [ customAppAliases[`${PAGES_DIR_ALIAS}/_error`] = [
...(pagesDir ...(pagesDir
...@@ -802,9 +804,7 @@ export default async function getBaseWebpackConfig( ...@@ -802,9 +804,7 @@ export default async function getBaseWebpackConfig(
return prev return prev
}, [] as string[]) }, [] as string[])
: []), : []),
isEdgeServer 'next/dist/pages/_error.js',
? 'next/dist/esm/pages/_error.js'
: 'next/dist/pages/_error.js',
] ]
customDocumentAliases[`${PAGES_DIR_ALIAS}/_document`] = [ customDocumentAliases[`${PAGES_DIR_ALIAS}/_document`] = [
...(pagesDir ...(pagesDir
...@@ -813,9 +813,7 @@ export default async function getBaseWebpackConfig( ...@@ -813,9 +813,7 @@ export default async function getBaseWebpackConfig(
return prev return prev
}, [] as string[]) }, [] as string[])
: []), : []),
isEdgeServer `next/dist/pages/_document.js`,
? `next/dist/esm/pages/_document.js`
: `next/dist/pages/_document.js`,
] ]
} }
......
...@@ -120,9 +120,8 @@ const nextAppLoader: webpack.LoaderDefinitionFunction<{ ...@@ -120,9 +120,8 @@ const nextAppLoader: webpack.LoaderDefinitionFunction<{
appDir: string appDir: string
appPaths: string[] | null appPaths: string[] | null
pageExtensions: string[] pageExtensions: string[]
nextRuntime: string
}> = async function nextAppLoader() { }> = async function nextAppLoader() {
const { name, appDir, appPaths, pagePath, pageExtensions, nextRuntime } = const { name, appDir, appPaths, pagePath, pageExtensions } =
this.getOptions() || {} this.getOptions() || {}
const buildInfo = getModuleBuildInfo((this as any)._module) const buildInfo = getModuleBuildInfo((this as any)._module)
...@@ -180,24 +179,23 @@ const nextAppLoader: webpack.LoaderDefinitionFunction<{ ...@@ -180,24 +179,23 @@ const nextAppLoader: webpack.LoaderDefinitionFunction<{
resolveParallelSegments, resolveParallelSegments,
}) })
const rootDistFolder = nextRuntime === 'edge' ? 'next/dist/esm' : 'next/dist'
const result = ` const result = `
export ${treeCode} export ${treeCode}
export const AppRouter = require('${rootDistFolder}/client/components/app-router.client.js').default export const AppRouter = require('next/dist/client/components/app-router.client.js').default
export const LayoutRouter = require('${rootDistFolder}/client/components/layout-router.client.js').default export const LayoutRouter = require('next/dist/client/components/layout-router.client.js').default
export const RenderFromTemplateContext = require('${rootDistFolder}/client/components/render-from-template-context.client.js').default export const RenderFromTemplateContext = require('next/dist/client/components/render-from-template-context.client.js').default
export const HotReloader = ${ export const HotReloader = ${
// Disable HotReloader component in production // Disable HotReloader component in production
this.mode === 'development' this.mode === 'development'
? `require('${rootDistFolder}/client/components/hot-reloader.client.js').default` ? `require('next/dist/client/components/hot-reloader.client.js').default`
: 'null' : 'null'
} }
export const staticGenerationAsyncStorage = require('${rootDistFolder}/client/components/static-generation-async-storage.js').staticGenerationAsyncStorage export const staticGenerationAsyncStorage = require('next/dist/client/components/static-generation-async-storage.js').staticGenerationAsyncStorage
export const requestAsyncStorage = require('${rootDistFolder}/client/components/request-async-storage.js').requestAsyncStorage export const requestAsyncStorage = require('next/dist/client/components/request-async-storage.js').requestAsyncStorage
export const serverHooks = require('${rootDistFolder}/client/components/hooks-server-context.js') export const serverHooks = require('next/dist/client/components/hooks-server-context.js')
export const renderToReadableStream = require('next/dist/compiled/react-server-dom-webpack/writer.browser.server').renderToReadableStream export const renderToReadableStream = require('next/dist/compiled/react-server-dom-webpack/writer.browser.server').renderToReadableStream
export const __next_app_webpack_require__ = __webpack_require__ export const __next_app_webpack_require__ = __webpack_require__
......
...@@ -18,18 +18,6 @@ export type EdgeSSRLoaderQuery = { ...@@ -18,18 +18,6 @@ export type EdgeSSRLoaderQuery = {
hasFontLoaders: boolean hasFontLoaders: boolean
} }
/*
For pages SSR'd at the edge, we bundle them with the ESM version of Next in order to
benefit from the better tree-shaking and thus, smaller bundle sizes.
The absolute paths for _app, _error and _document, used in this loader, link to the regular CJS modules.
They are generated in `createPagesMapping` where we don't have access to `isEdgeRuntime`,
so we have to do it here. It's not that bad because it keeps all references to ESM modules magic in this place.
*/
function swapDistFolderWithEsmDistFolder(path: string) {
return path.replace('next/dist/pages', 'next/dist/esm/pages')
}
export default async function edgeSSRLoader(this: any) { export default async function edgeSSRLoader(this: any) {
const { const {
dev, dev,
...@@ -66,18 +54,9 @@ export default async function edgeSSRLoader(this: any) { ...@@ -66,18 +54,9 @@ export default async function edgeSSRLoader(this: any) {
} }
const stringifiedPagePath = stringifyRequest(this, absolutePagePath) const stringifiedPagePath = stringifyRequest(this, absolutePagePath)
const stringifiedAppPath = stringifyRequest( const stringifiedAppPath = stringifyRequest(this, absoluteAppPath)
this, const stringifiedErrorPath = stringifyRequest(this, absoluteErrorPath)
swapDistFolderWithEsmDistFolder(absoluteAppPath) const stringifiedDocumentPath = stringifyRequest(this, absoluteDocumentPath)
)
const stringifiedErrorPath = stringifyRequest(
this,
swapDistFolderWithEsmDistFolder(absoluteErrorPath)
)
const stringifiedDocumentPath = stringifyRequest(
this,
swapDistFolderWithEsmDistFolder(absoluteDocumentPath)
)
const stringified500Path = absolute500Path const stringified500Path = absolute500Path
? stringifyRequest(this, absolute500Path) ? stringifyRequest(this, absolute500Path)
: null : null
...@@ -88,8 +67,8 @@ export default async function edgeSSRLoader(this: any) { ...@@ -88,8 +67,8 @@ export default async function edgeSSRLoader(this: any) {
)}` )}`
const transformed = ` const transformed = `
import { adapter, enhanceGlobals } from 'next/dist/esm/server/web/adapter' import { adapter, enhanceGlobals } from 'next/dist/server/web/adapter'
import { getRender } from 'next/dist/esm/build/webpack/loaders/next-edge-ssr-loader/render' import { getRender } from 'next/dist/build/webpack/loaders/next-edge-ssr-loader/render'
enhanceGlobals() enhanceGlobals()
...@@ -98,7 +77,7 @@ export default async function edgeSSRLoader(this: any) { ...@@ -98,7 +77,7 @@ export default async function edgeSSRLoader(this: any) {
isAppDir isAppDir
? ` ? `
const Document = null const Document = null
const appRenderToHTML = require('next/dist/esm/server/app-render').renderToHTMLOrFlight const appRenderToHTML = require('next/dist/server/app-render').renderToHTMLOrFlight
const pagesRenderToHTML = null const pagesRenderToHTML = null
const pageMod = require(${JSON.stringify(pageModPath)}) const pageMod = require(${JSON.stringify(pageModPath)})
const appMod = null const appMod = null
...@@ -108,7 +87,7 @@ export default async function edgeSSRLoader(this: any) { ...@@ -108,7 +87,7 @@ export default async function edgeSSRLoader(this: any) {
: ` : `
const Document = require(${stringifiedDocumentPath}).default const Document = require(${stringifiedDocumentPath}).default
const appRenderToHTML = null const appRenderToHTML = null
const pagesRenderToHTML = require('next/dist/esm/server/render').renderToHTML const pagesRenderToHTML = require('next/dist/server/render').renderToHTML
const pageMod = require(${stringifiedPagePath}) const pageMod = require(${stringifiedPagePath})
const appMod = require(${stringifiedAppPath}) const appMod = require(${stringifiedAppPath})
const errorMod = require(${stringifiedErrorPath}) const errorMod = require(${stringifiedErrorPath})
......
import type { NextConfig } from '../../../../server/config-shared' import type { NextConfig } from '../../../../server/config-shared'
import type { DocumentType, AppType } from '../../../../shared/lib/utils' import type { DocumentType, AppType } from '../../../../shared/lib/utils'
import type { BuildManifest } from '../../../../server/get-page-files' import type { BuildManifest } from '../../../../server/get-page-files'
import type { ReactLoadableManifest } from '../../../../server/load-components' import type { ReactLoadableManifest } from '../../../../server/load-components'
......
...@@ -307,19 +307,9 @@ export class FlightClientEntryPlugin { ...@@ -307,19 +307,9 @@ export class FlightClientEntryPlugin {
modules: clientComponentImports, modules: clientComponentImports,
server: false, server: false,
} }
const clientLoader = `next-flight-client-entry-loader?${stringify(
// For the client entry, we always use the CJS build of Next.js. If the loaderOptions
// server is using the ESM build (when using the Edge runtime), we need to )}!`
// replace them.
const clientLoader = `next-flight-client-entry-loader?${stringify({
modules: this.isEdgeServer
? clientComponentImports.map((importPath) =>
importPath.replace('next/dist/esm/', 'next/dist/')
)
: clientComponentImports,
server: false,
})}!`
const clientSSRLoader = `next-flight-client-entry-loader?${stringify({ const clientSSRLoader = `next-flight-client-entry-loader?${stringify({
...loaderOptions, ...loaderOptions,
server: true, server: true,
......
...@@ -56,9 +56,6 @@ export type FlightManifest = { ...@@ -56,9 +56,6 @@ export type FlightManifest = {
__ssr_module_mapping__: { __ssr_module_mapping__: {
[moduleId: string]: ManifestNode [moduleId: string]: ManifestNode
} }
__edge_ssr_module_mapping__: {
[moduleId: string]: ManifestNode
}
} & { } & {
[modulePath: string]: ManifestNode [modulePath: string]: ManifestNode
} }
...@@ -144,7 +141,6 @@ export class FlightManifestPlugin { ...@@ -144,7 +141,6 @@ export class FlightManifestPlugin {
) { ) {
const manifest: FlightManifest = { const manifest: FlightManifest = {
__ssr_module_mapping__: {}, __ssr_module_mapping__: {},
__edge_ssr_module_mapping__: {},
} }
const dev = this.dev const dev = this.dev
const fontLoaderTargets = this.fontLoaderTargets const fontLoaderTargets = this.fontLoaderTargets
...@@ -200,7 +196,6 @@ export class FlightManifestPlugin { ...@@ -200,7 +196,6 @@ export class FlightManifestPlugin {
const moduleExports = manifest[resource] || {} const moduleExports = manifest[resource] || {}
const moduleIdMapping = manifest.__ssr_module_mapping__ const moduleIdMapping = manifest.__ssr_module_mapping__
const edgeModuleIdMapping = manifest.__edge_ssr_module_mapping__
// Note that this isn't that reliable as webpack is still possible to assign // Note that this isn't that reliable as webpack is still possible to assign
// additional queries to make sure there's no conflict even using the `named` // additional queries to make sure there's no conflict even using the `named`
...@@ -309,25 +304,10 @@ export class FlightManifestPlugin { ...@@ -309,25 +304,10 @@ export class FlightManifestPlugin {
...moduleExports[name], ...moduleExports[name],
id: ssrNamedModuleId, id: ssrNamedModuleId,
} }
edgeModuleIdMapping[id] = edgeModuleIdMapping[id] || {}
edgeModuleIdMapping[id][name] = {
...moduleExports[name],
id: ssrNamedModuleId.replace(/\/next\/dist\//, '/next/dist/esm/'),
}
}) })
manifest[resource] = moduleExports manifest[resource] = moduleExports
// The client compiler will always use the CJS Next.js build, so here we
// also add the mapping for the ESM build (Edge runtime) to consume.
if (/\/next\/dist\//.test(resource)) {
manifest[resource.replace(/\/next\/dist\//, '/next/dist/esm/')] =
moduleExports
}
manifest.__ssr_module_mapping__ = moduleIdMapping manifest.__ssr_module_mapping__ = moduleIdMapping
manifest.__edge_ssr_module_mapping__ = edgeModuleIdMapping
} }
chunkGroup.chunks.forEach((chunk: webpack.Chunk) => { chunkGroup.chunks.forEach((chunk: webpack.Chunk) => {
......
...@@ -110,15 +110,11 @@ function findFeatureInModule(module: Module): Feature | undefined { ...@@ -110,15 +110,11 @@ function findFeatureInModule(module: Module): Feature | undefined {
* dependency. * dependency.
*/ */
function findUniqueOriginModulesInConnections( function findUniqueOriginModulesInConnections(
connections: Connection[], connections: Connection[]
originModule: Module
): Set<unknown> { ): Set<unknown> {
const originModules = new Set() const originModules = new Set()
for (const connection of connections) { for (const connection of connections) {
if ( if (!originModules.has(connection.originModule)) {
!originModules.has(connection.originModule) &&
connection.originModule !== originModule
) {
originModules.add(connection.originModule) originModules.add(connection.originModule)
} }
} }
...@@ -165,10 +161,8 @@ export class TelemetryPlugin implements webpack.WebpackPluginInstance { ...@@ -165,10 +161,8 @@ export class TelemetryPlugin implements webpack.WebpackPluginInstance {
const connections = ( const connections = (
compilation as any compilation as any
).moduleGraph.getIncomingConnections(module) ).moduleGraph.getIncomingConnections(module)
const originModules = findUniqueOriginModulesInConnections( const originModules =
connections, findUniqueOriginModulesInConnections(connections)
module
)
this.usageTracker.get(feature)!.invocationCount = this.usageTracker.get(feature)!.invocationCount =
originModules.size originModules.size
} }
......
module.exports = module.exports = require('./dist/client/index')
process.env.NEXT_RUNTIME === 'edge'
? require('./dist/esm/client/index')
: require('./dist/client/index')
module.exports = module.exports = require('./dist/shared/lib/runtime-config')
process.env.NEXT_RUNTIME === 'edge'
? require('./dist/esm/shared/lib/runtime-config')
: require('./dist/shared/lib/runtime-config')
module.exports = module.exports = require('./dist/shared/lib/constants')
process.env.NEXT_RUNTIME === 'edge'
? require('./dist/esm/shared/lib/constants')
: require('./dist/shared/lib/constants')
module.exports = module.exports = require('./dist/pages/_document')
process.env.NEXT_RUNTIME === 'edge'
? require('./dist/esm/pages/_document')
: require('./dist/pages/_document')
module.exports = module.exports = require('./dist/shared/lib/dynamic')
process.env.NEXT_RUNTIME === 'edge'
? require('./dist/esm/shared/lib/dynamic')
: require('./dist/shared/lib/dynamic')
module.exports = module.exports = require('./dist/pages/_error')
process.env.NEXT_RUNTIME === 'edge'
? require('./dist/esm/pages/_error')
: require('./dist/pages/_error')
module.exports = module.exports = require('./dist/shared/lib/head')
process.env.NEXT_RUNTIME === 'edge'
? require('./dist/esm/shared/lib/head')
: require('./dist/shared/lib/head')
module.exports = module.exports = require('./dist/client/image')
process.env.NEXT_RUNTIME === 'edge'
? require('./dist/esm/client/image')
: require('./dist/client/image')
module.exports = module.exports = require('./dist/client/link')
process.env.NEXT_RUNTIME === 'edge'
? require('./dist/esm/client/link')
: require('./dist/client/link')
import React from 'react' import React from 'react'
import {
import type { loadGetInitialProps,
AppContextType, AppContextType,
AppInitialProps, AppInitialProps,
AppPropsType, AppPropsType,
...@@ -9,8 +9,6 @@ import type { ...@@ -9,8 +9,6 @@ import type {
} from '../shared/lib/utils' } from '../shared/lib/utils'
import type { Router } from '../client/router' import type { Router } from '../client/router'
import { loadGetInitialProps } from '../shared/lib/utils'
export { AppInitialProps, AppType } export { AppInitialProps, AppType }
export { NextWebVitalsMetric } export { NextWebVitalsMetric }
......
module.exports = module.exports = require('./dist/client/router')
process.env.NEXT_RUNTIME === 'edge'
? require('./dist/esm/client/router')
: require('./dist/client/router')
module.exports = module.exports = require('./dist/client/script')
process.env.NEXT_RUNTIME === 'edge'
? require('./dist/esm/client/script')
: require('./dist/client/script')
...@@ -258,10 +258,7 @@ function useFlightResponse( ...@@ -258,10 +258,7 @@ function useFlightResponse(
const [renderStream, forwardStream] = readableStreamTee(req) const [renderStream, forwardStream] = readableStreamTee(req)
const res = createFromReadableStream(renderStream, { const res = createFromReadableStream(renderStream, {
moduleMap: moduleMap: serverComponentManifest.__ssr_module_mapping__,
process.env.NEXT_RUNTIME === 'edge'
? serverComponentManifest.__edge_ssr_module_mapping__
: serverComponentManifest.__ssr_module_mapping__,
}) })
flightResponseRef.current = res flightResponseRef.current = res
...@@ -273,7 +270,7 @@ function useFlightResponse( ...@@ -273,7 +270,7 @@ function useFlightResponse(
? `<script nonce=${JSON.stringify(nonce)}>` ? `<script nonce=${JSON.stringify(nonce)}>`
: '<script>' : '<script>'
function read() { function process() {
forwardReader.read().then(({ done, value }) => { forwardReader.read().then(({ done, value }) => {
if (value) { if (value) {
rscChunks.push(value) rscChunks.push(value)
...@@ -299,11 +296,11 @@ function useFlightResponse( ...@@ -299,11 +296,11 @@ function useFlightResponse(
)})</script>` )})</script>`
writer.write(encodeText(scripts)) writer.write(encodeText(scripts))
read() process()
} }
}) })
} }
read() process()
return res return res
} }
......
...@@ -626,7 +626,6 @@ export default class HotReloader { ...@@ -626,7 +626,6 @@ export default class HotReloader {
), ),
appDir: this.appDir!, appDir: this.appDir!,
pageExtensions: this.config.pageExtensions, pageExtensions: this.config.pageExtensions,
nextRuntime: 'edge',
}).import }).import
: undefined : undefined
...@@ -706,7 +705,6 @@ export default class HotReloader { ...@@ -706,7 +705,6 @@ export default class HotReloader {
), ),
appDir: this.appDir!, appDir: this.appDir!,
pageExtensions: this.config.pageExtensions, pageExtensions: this.config.pageExtensions,
nextRuntime: 'nodejs',
}) })
: relativeRequest, : relativeRequest,
appDir: this.config.experimental.appDir, appDir: this.config.experimental.appDir,
......
...@@ -18,7 +18,6 @@ module.exports = function (task) { ...@@ -18,7 +18,6 @@ module.exports = function (task) {
stripExtension, stripExtension,
keepImportAssertions = false, keepImportAssertions = false,
interopClientDefaultExport = false, interopClientDefaultExport = false,
esm = false,
} = {} } = {}
) { ) {
// Don't compile .d.ts // Don't compile .d.ts
...@@ -29,7 +28,7 @@ module.exports = function (task) { ...@@ -29,7 +28,7 @@ module.exports = function (task) {
/** @type {import('@swc/core').Options} */ /** @type {import('@swc/core').Options} */
const swcClientOptions = { const swcClientOptions = {
module: { module: {
type: esm ? 'es6' : 'commonjs', type: 'commonjs',
ignoreDynamic: true, ignoreDynamic: true,
}, },
jsc: { jsc: {
...@@ -60,7 +59,7 @@ module.exports = function (task) { ...@@ -60,7 +59,7 @@ module.exports = function (task) {
/** @type {import('@swc/core').Options} */ /** @type {import('@swc/core').Options} */
const swcServerOptions = { const swcServerOptions = {
module: { module: {
type: esm ? 'es6' : 'commonjs', type: 'commonjs',
ignoreDynamic: true, ignoreDynamic: true,
}, },
env: { env: {
...@@ -127,7 +126,7 @@ module.exports = function (task) { ...@@ -127,7 +126,7 @@ module.exports = function (task) {
} }
if (output.map) { if (output.map) {
if (interopClientDefaultExport && !esm) { if (interopClientDefaultExport) {
output.code += ` output.code += `
if ((typeof exports.default === 'function' || (typeof exports.default === 'object' && exports.default !== null)) && typeof exports.default.__esModule === 'undefined') { if ((typeof exports.default === 'function' || (typeof exports.default === 'object' && exports.default !== null)) && typeof exports.default.__esModule === 'undefined') {
Object.defineProperty(exports.default, '__esModule', { value: true }); Object.defineProperty(exports.default, '__esModule', { value: true });
......
...@@ -1946,23 +1946,16 @@ export async function compile(task, opts) { ...@@ -1946,23 +1946,16 @@ export async function compile(task, opts) {
'cli', 'cli',
'bin', 'bin',
'server', 'server',
'server_esm',
'nextbuild', 'nextbuild',
'nextbuildjest', 'nextbuildjest',
'nextbuildstatic', 'nextbuildstatic',
'nextbuild_esm',
'pages', 'pages',
'pages_esm',
'lib', 'lib',
'lib_esm',
'client', 'client',
'client_esm',
'telemetry', 'telemetry',
'trace', 'trace',
'shared', 'shared',
'shared_esm',
'shared_re_exported', 'shared_re_exported',
'shared_re_exported_esm',
'server_wasm', 'server_wasm',
// we compile this each time so that fresh runtime data is pulled // we compile this each time so that fresh runtime data is pulled
// before each publish // before each publish
...@@ -1997,14 +1990,6 @@ export async function lib(task, opts) { ...@@ -1997,14 +1990,6 @@ export async function lib(task, opts) {
notify('Compiled lib files') notify('Compiled lib files')
} }
export async function lib_esm(task, opts) {
await task
.source(opts.src || 'lib/**/*.+(js|ts|tsx)')
.swc('server', { dev: opts.dev, esm: true })
.target('dist/esm/lib')
notify('Compiled lib files')
}
export async function server(task, opts) { export async function server(task, opts) {
await task await task
.source(opts.src || 'server/**/*.+(js|ts|tsx)') .source(opts.src || 'server/**/*.+(js|ts|tsx)')
...@@ -2019,14 +2004,6 @@ export async function server(task, opts) { ...@@ -2019,14 +2004,6 @@ export async function server(task, opts) {
notify('Compiled server files') notify('Compiled server files')
} }
export async function server_esm(task, opts) {
await task
.source(opts.src || 'server/**/*.+(js|ts|tsx)')
.swc('server', { dev: opts.dev, esm: true })
.target('dist/esm/server')
notify('Compiled server files to ESM')
}
export async function nextbuild(task, opts) { export async function nextbuild(task, opts) {
await task await task
.source(opts.src || 'build/**/*.+(js|ts|tsx)', { .source(opts.src || 'build/**/*.+(js|ts|tsx)', {
...@@ -2037,16 +2014,6 @@ export async function nextbuild(task, opts) { ...@@ -2037,16 +2014,6 @@ export async function nextbuild(task, opts) {
notify('Compiled build files') notify('Compiled build files')
} }
export async function nextbuild_esm(task, opts) {
await task
.source(opts.src || 'build/**/*.+(js|ts|tsx)', {
ignore: ['**/fixture/**', '**/tests/**', '**/jest/**'],
})
.swc('server', { dev: opts.dev, esm: true })
.target('dist/esm/build')
notify('Compiled build files to ESM')
}
export async function nextbuildjest(task, opts) { export async function nextbuildjest(task, opts) {
await task await task
.source(opts.src || 'build/jest/**/*.+(js|ts|tsx)', { .source(opts.src || 'build/jest/**/*.+(js|ts|tsx)', {
...@@ -2065,14 +2032,6 @@ export async function client(task, opts) { ...@@ -2065,14 +2032,6 @@ export async function client(task, opts) {
notify('Compiled client files') notify('Compiled client files')
} }
export async function client_esm(task, opts) {
await task
.source(opts.src || 'client/**/*.+(js|ts|tsx)')
.swc('client', { dev: opts.dev, esm: true })
.target('dist/esm/client')
notify('Compiled client files to ESM')
}
// export is a reserved keyword for functions // export is a reserved keyword for functions
export async function nextbuildstatic(task, opts) { export async function nextbuildstatic(task, opts) {
await task await task
...@@ -2103,38 +2062,10 @@ export async function pages_document(task, opts) { ...@@ -2103,38 +2062,10 @@ export async function pages_document(task, opts) {
.target('dist/pages') .target('dist/pages')
} }
export async function pages_app_esm(task, opts) {
await task
.source('pages/_app.tsx')
.swc('client', { dev: opts.dev, keepImportAssertions: true, esm: true })
.target('dist/esm/pages')
}
export async function pages_error_esm(task, opts) {
await task
.source('pages/_error.tsx')
.swc('client', { dev: opts.dev, keepImportAssertions: true, esm: true })
.target('dist/esm/pages')
}
export async function pages_document_esm(task, opts) {
await task
.source('pages/_document.tsx')
.swc('server', { dev: opts.dev, keepImportAssertions: true, esm: true })
.target('dist/esm/pages')
}
export async function pages(task, opts) { export async function pages(task, opts) {
await task.parallel(['pages_app', 'pages_error', 'pages_document'], opts) await task.parallel(['pages_app', 'pages_error', 'pages_document'], opts)
} }
export async function pages_esm(task, opts) {
await task.parallel(
['pages_app_esm', 'pages_error_esm', 'pages_document_esm'],
opts
)
}
export async function telemetry(task, opts) { export async function telemetry(task, opts) {
await task await task
.source(opts.src || 'telemetry/**/*.+(js|ts|tsx)') .source(opts.src || 'telemetry/**/*.+(js|ts|tsx)')
...@@ -2162,15 +2093,11 @@ export default async function (task) { ...@@ -2162,15 +2093,11 @@ export default async function (task) {
await task.watch('bin/*', 'bin', opts) await task.watch('bin/*', 'bin', opts)
await task.watch('pages/**/*.+(js|ts|tsx)', 'pages', opts) await task.watch('pages/**/*.+(js|ts|tsx)', 'pages', opts)
await task.watch('server/**/*.+(js|ts|tsx)', 'server', opts) await task.watch('server/**/*.+(js|ts|tsx)', 'server', opts)
await task.watch('server/**/*.+(js|ts|tsx)', 'server_esm', opts)
await task.watch('build/**/*.+(js|ts|tsx)', 'nextbuild', opts) await task.watch('build/**/*.+(js|ts|tsx)', 'nextbuild', opts)
await task.watch('build/**/*.+(js|ts|tsx)', 'nextbuild_esm', opts)
await task.watch('build/jest/**/*.+(js|ts|tsx)', 'nextbuildjest', opts) await task.watch('build/jest/**/*.+(js|ts|tsx)', 'nextbuildjest', opts)
await task.watch('export/**/*.+(js|ts|tsx)', 'nextbuildstatic', opts) await task.watch('export/**/*.+(js|ts|tsx)', 'nextbuildstatic', opts)
await task.watch('client/**/*.+(js|ts|tsx)', 'client', opts) await task.watch('client/**/*.+(js|ts|tsx)', 'client', opts)
await task.watch('client/**/*.+(js|ts|tsx)', 'client_esm', opts)
await task.watch('lib/**/*.+(js|ts|tsx)', 'lib', opts) await task.watch('lib/**/*.+(js|ts|tsx)', 'lib', opts)
await task.watch('lib/**/*.+(js|ts|tsx)', 'lib_esm', opts)
await task.watch('cli/**/*.+(js|ts|tsx)', 'cli', opts) await task.watch('cli/**/*.+(js|ts|tsx)', 'cli', opts)
await task.watch('telemetry/**/*.+(js|ts|tsx)', 'telemetry', opts) await task.watch('telemetry/**/*.+(js|ts|tsx)', 'telemetry', opts)
await task.watch('trace/**/*.+(js|ts|tsx)', 'trace', opts) await task.watch('trace/**/*.+(js|ts|tsx)', 'trace', opts)
...@@ -2184,16 +2111,6 @@ export default async function (task) { ...@@ -2184,16 +2111,6 @@ export default async function (task) {
'shared', 'shared',
opts opts
) )
await task.watch(
'shared/**/!(amp|config|constants|dynamic|head).+(js|ts|tsx)',
'shared_esm',
opts
)
await task.watch(
'shared/lib/{amp,config,constants,dynamic,head}.+(js|ts|tsx)',
'shared_re_exported_esm',
opts
)
await task.watch('server/**/*.+(wasm)', 'server_wasm', opts) await task.watch('server/**/*.+(wasm)', 'server_wasm', opts)
await task.watch( await task.watch(
'../react-dev-overlay/dist/**/*.js', '../react-dev-overlay/dist/**/*.js',
...@@ -2213,16 +2130,6 @@ export async function shared(task, opts) { ...@@ -2213,16 +2130,6 @@ export async function shared(task, opts) {
notify('Compiled shared files') notify('Compiled shared files')
} }
export async function shared_esm(task, opts) {
await task
.source(
opts.src || 'shared/**/!(amp|config|constants|dynamic|head).+(js|ts|tsx)'
)
.swc('client', { dev: opts.dev, esm: true })
.target('dist/esm/shared')
notify('Compiled shared files to ESM')
}
export async function shared_re_exported(task, opts) { export async function shared_re_exported(task, opts) {
await task await task
.source( .source(
...@@ -2234,19 +2141,6 @@ export async function shared_re_exported(task, opts) { ...@@ -2234,19 +2141,6 @@ export async function shared_re_exported(task, opts) {
notify('Compiled shared re-exported files') notify('Compiled shared re-exported files')
} }
export async function shared_re_exported_esm(task, opts) {
await task
.source(
opts.src || 'shared/**/{amp,config,constants,dynamic,head}.+(js|ts|tsx)'
)
.swc('client', {
dev: opts.dev,
esm: true,
})
.target('dist/esm/shared')
notify('Compiled shared re-exported files as ESM')
}
export async function server_wasm(task, opts) { export async function server_wasm(task, opts) {
await task.source(opts.src || 'server/**/*.+(wasm)').target('dist/server') await task.source(opts.src || 'server/**/*.+(wasm)').target('dist/server')
notify('Moved server wasm files') notify('Moved server wasm files')
......
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