Unverified Commit 4f212ee9 authored by Tobias Koppers's avatar Tobias Koppers Committed by GitHub

the way towards webpack 5 typings (#29105)

Co-authored-by: 's avatarsokra <sokra@users.noreply.github.com>
parent 90a3b50c
packages/next/bundles/** -text
packages/next/compiled/** -text
...@@ -53,7 +53,9 @@ jobs: ...@@ -53,7 +53,9 @@ jobs:
- uses: actions/cache@v2 - uses: actions/cache@v2
id: cache-build id: cache-build
with: with:
path: ./* path: |
./*
!./.git
key: ${{ github.sha }} key: ${{ github.sha }}
lint: lint:
...@@ -63,7 +65,9 @@ jobs: ...@@ -63,7 +65,9 @@ jobs:
- uses: actions/cache@v2 - uses: actions/cache@v2
id: restore-build id: restore-build
with: with:
path: ./* path: |
./*
!./.git
key: ${{ github.sha }} key: ${{ github.sha }}
- run: ./scripts/check-manifests.js - run: ./scripts/check-manifests.js
- run: yarn lint - run: yarn lint
...@@ -75,29 +79,44 @@ jobs: ...@@ -75,29 +79,44 @@ jobs:
env: env:
NEXT_TELEMETRY_DISABLED: 1 NEXT_TELEMETRY_DISABLED: 1
steps: steps:
- uses: actions/checkout@v2
if: ${{needs.build.outputs.docsChange != 'docs only change'}}
# https://github.com/actions/virtual-environments/issues/1187 # https://github.com/actions/virtual-environments/issues/1187
- name: tune linux network - name: tune linux network
if: ${{needs.build.outputs.docsChange != 'docs only change'}}
run: sudo ethtool -K eth0 tx off rx off run: sudo ethtool -K eth0 tx off rx off
- uses: actions/cache@v2 - uses: actions/cache@v2
if: ${{needs.build.outputs.docsChange != 'docs only change'}} if: ${{needs.build.outputs.docsChange != 'docs only change'}}
id: restore-build id: restore-build
with: with:
path: ./* path: |
./*
!./.git
key: ${{ github.sha }} key: ${{ github.sha }}
- uses: actions/download-artifact@v2 - uses: actions/download-artifact@v2
if: ${{needs.build.outputs.docsChange != 'docs only change'}} if: ${{needs.build.outputs.docsChange != 'docs only change'}}
with: with:
name: next-swc-binaries name: next-swc-binaries
path: packages/next/build/swc/dist path: packages/next/build/swc/dist
# Only check linux build for now, mac builds can sometimes be different even with the same code # Only check linux build for now, mac builds can sometimes be different even with the same code
- run: | - run: |
mv ./packages/next/build/swc/dist/next-swc.linux-x64-gnu.node \ mv ./packages/next/build/swc/dist/next-swc.linux-x64-gnu.node \
./packages/next/native/next-swc.linux-x64-gnu.node ./packages/next/native/next-swc.linux-x64-gnu.node
if: ${{needs.build.outputs.docsChange != 'docs only change'}} if: ${{needs.build.outputs.docsChange != 'docs only change'}}
- run: ./scripts/check-pre-compiled.sh - run: ./scripts/check-pre-compiled.sh
if: ${{needs.build.outputs.docsChange != 'docs only change'}} if: ${{needs.build.outputs.docsChange != 'docs only change'}}
- uses: EndBug/add-and-commit@v7
if: ${{ failure() }}
with:
add: 'packages/next/compiled packages/next/bundles --force'
message: '⚙ Update compiled files'
testUnit: testUnit:
name: Test Unit name: Test Unit
runs-on: ubuntu-latest runs-on: ubuntu-latest
...@@ -110,7 +129,9 @@ jobs: ...@@ -110,7 +129,9 @@ jobs:
if: ${{needs.build.outputs.docsChange != 'docs only change'}} if: ${{needs.build.outputs.docsChange != 'docs only change'}}
id: restore-build id: restore-build
with: with:
path: ./* path: |
./*
!./.git
key: ${{ github.sha }} key: ${{ github.sha }}
- run: node run-tests.js --type unit - run: node run-tests.js --type unit
...@@ -134,7 +155,9 @@ jobs: ...@@ -134,7 +155,9 @@ jobs:
if: ${{needs.build.outputs.docsChange != 'docs only change'}} if: ${{needs.build.outputs.docsChange != 'docs only change'}}
id: restore-build id: restore-build
with: with:
path: ./* path: |
./*
!./.git
key: ${{ github.sha }} key: ${{ github.sha }}
- run: npm i -g playwright-chromium@1.14.1 && npx playwright install-deps - run: npm i -g playwright-chromium@1.14.1 && npx playwright install-deps
...@@ -170,7 +193,9 @@ jobs: ...@@ -170,7 +193,9 @@ jobs:
if: ${{needs.build.outputs.docsChange != 'docs only change'}} if: ${{needs.build.outputs.docsChange != 'docs only change'}}
id: restore-build id: restore-build
with: with:
path: ./* path: |
./*
!./.git
key: ${{ github.sha }} key: ${{ github.sha }}
- run: npm i -g playwright-chromium@1.14.1 && npx playwright install-deps - run: npm i -g playwright-chromium@1.14.1 && npx playwright install-deps
...@@ -210,7 +235,9 @@ jobs: ...@@ -210,7 +235,9 @@ jobs:
if: ${{needs.build.outputs.docsChange != 'docs only change'}} if: ${{needs.build.outputs.docsChange != 'docs only change'}}
id: restore-build id: restore-build
with: with:
path: ./* path: |
./*
!./.git
key: ${{ github.sha }} key: ${{ github.sha }}
- run: npm i -g playwright-chromium@1.14.1 && npx playwright install-deps - run: npm i -g playwright-chromium@1.14.1 && npx playwright install-deps
...@@ -236,7 +263,9 @@ jobs: ...@@ -236,7 +263,9 @@ jobs:
if: ${{needs.build.outputs.docsChange != 'docs only change'}} if: ${{needs.build.outputs.docsChange != 'docs only change'}}
id: restore-build id: restore-build
with: with:
path: ./* path: |
./*
!./.git
key: ${{ github.sha }} key: ${{ github.sha }}
# TODO: remove after we fix watchpack watching too much # TODO: remove after we fix watchpack watching too much
...@@ -260,7 +289,9 @@ jobs: ...@@ -260,7 +289,9 @@ jobs:
if: ${{needs.build.outputs.docsChange != 'docs only change'}} if: ${{needs.build.outputs.docsChange != 'docs only change'}}
id: restore-build id: restore-build
with: with:
path: ./* path: |
./*
!./.git
key: ${{ github.sha }} key: ${{ github.sha }}
- run: bash ./scripts/test-pnp.sh - run: bash ./scripts/test-pnp.sh
...@@ -272,6 +303,8 @@ jobs: ...@@ -272,6 +303,8 @@ jobs:
needs: needs:
[ [
lint, lint,
check-examples,
test-native,
checkPrecompiled, checkPrecompiled,
testIntegration, testIntegration,
testUnit, testUnit,
...@@ -300,7 +333,9 @@ jobs: ...@@ -300,7 +333,9 @@ jobs:
if: ${{needs.build.outputs.docsChange != 'docs only change'}} if: ${{needs.build.outputs.docsChange != 'docs only change'}}
id: restore-build id: restore-build
with: with:
path: ./* path: |
./*
!./.git
key: ${{ github.sha }} key: ${{ github.sha }}
- run: npm i -g playwright-chromium@1.14.1 && npx playwright install-deps - run: npm i -g playwright-chromium@1.14.1 && npx playwright install-deps
...@@ -321,7 +356,9 @@ jobs: ...@@ -321,7 +356,9 @@ jobs:
if: ${{needs.build.outputs.docsChange != 'docs only change'}} if: ${{needs.build.outputs.docsChange != 'docs only change'}}
id: restore-build id: restore-build
with: with:
path: ./* path: |
./*
!./.git
key: ${{ github.sha }} key: ${{ github.sha }}
- run: npx playwright install-deps && npx playwright install firefox - run: npx playwright install-deps && npx playwright install firefox
if: ${{needs.build.outputs.docsChange != 'docs only change'}} if: ${{needs.build.outputs.docsChange != 'docs only change'}}
...@@ -348,7 +385,9 @@ jobs: ...@@ -348,7 +385,9 @@ jobs:
if: ${{needs.build.outputs.docsChange != 'docs only change'}} if: ${{needs.build.outputs.docsChange != 'docs only change'}}
id: restore-build id: restore-build
with: with:
path: ./* path: |
./*
!./.git
key: ${{ github.sha }} key: ${{ github.sha }}
# TODO: use macos runner so that we can use playwright to test against # TODO: use macos runner so that we can use playwright to test against
...@@ -380,7 +419,9 @@ jobs: ...@@ -380,7 +419,9 @@ jobs:
if: ${{needs.build.outputs.docsChange != 'docs only change'}} if: ${{needs.build.outputs.docsChange != 'docs only change'}}
id: restore-build id: restore-build
with: with:
path: ./* path: |
./*
!./.git
key: ${{ github.sha }} key: ${{ github.sha }}
- run: '[[ -z "$BROWSERSTACK_ACCESS_KEY" ]] && echo "Skipping for PR" || npm i -g browserstack-local@1.4.0' - run: '[[ -z "$BROWSERSTACK_ACCESS_KEY" ]] && echo "Skipping for PR" || npm i -g browserstack-local@1.4.0'
...@@ -404,7 +445,9 @@ jobs: ...@@ -404,7 +445,9 @@ jobs:
- uses: actions/cache@v2 - uses: actions/cache@v2
id: restore-build id: restore-build
with: with:
path: ./* path: |
./*
!./.git
key: ${{ github.sha }} key: ${{ github.sha }}
- uses: actions/download-artifact@v2 - uses: actions/download-artifact@v2
with: with:
...@@ -422,7 +465,9 @@ jobs: ...@@ -422,7 +465,9 @@ jobs:
- uses: actions/cache@v2 - uses: actions/cache@v2
id: restore-build id: restore-build
with: with:
path: ./* path: |
./*
!./.git
key: ${{ github.sha }} key: ${{ github.sha }}
- run: ./scripts/release-stats.sh - run: ./scripts/release-stats.sh
- uses: ./.github/actions/next-stats-action - uses: ./.github/actions/next-stats-action
......
{ {
"name": "nextjs-project", "name": "nextjs-project",
"version": "0.0.0",
"private": true, "private": true,
"workspaces": [ "workspaces": [
"packages/*" "packages/*"
...@@ -61,6 +62,24 @@ ...@@ -61,6 +62,24 @@
"@typescript-eslint/eslint-plugin": "4.29.1", "@typescript-eslint/eslint-plugin": "4.29.1",
"@typescript-eslint/parser": "4.29.1", "@typescript-eslint/parser": "4.29.1",
"@vercel/fetch": "6.1.1", "@vercel/fetch": "6.1.1",
"@webassemblyjs/ast": "1.11.1",
"@webassemblyjs/floating-point-hex-parser": "1.11.1",
"@webassemblyjs/helper-api-error": "1.11.1",
"@webassemblyjs/helper-buffer": "1.11.1",
"@webassemblyjs/helper-code-frame": "npm:empty-npm-package@1.0.0",
"@webassemblyjs/helper-module-context": "npm:empty-npm-package@1.0.0",
"@webassemblyjs/helper-numbers": "1.11.1",
"@webassemblyjs/helper-wasm-bytecode": "1.11.1",
"@webassemblyjs/helper-wasm-section": "1.11.1",
"@webassemblyjs/ieee754": "1.11.1",
"@webassemblyjs/leb128": "1.11.1",
"@webassemblyjs/utf8": "1.11.1",
"@webassemblyjs/wasm-edit": "1.11.1",
"@webassemblyjs/wasm-gen": "1.11.1",
"@webassemblyjs/wasm-opt": "1.11.1",
"@webassemblyjs/wasm-parser": "1.11.1",
"@webassemblyjs/wast-parser": "npm:empty-npm-package@1.0.0",
"@webassemblyjs/wast-printer": "1.11.1",
"@zeit/next-css": "1.0.2-canary.2", "@zeit/next-css": "1.0.2-canary.2",
"@zeit/next-sass": "1.0.2-canary.2", "@zeit/next-sass": "1.0.2-canary.2",
"@zeit/next-typescript": "1.1.2-canary.0", "@zeit/next-typescript": "1.1.2-canary.0",
...@@ -68,7 +87,7 @@ ...@@ -68,7 +87,7 @@
"alex": "9.1.0", "alex": "9.1.0",
"amphtml-validator": "1.0.33", "amphtml-validator": "1.0.33",
"async-sema": "3.0.1", "async-sema": "3.0.1",
"browserslist": "^4.14.7", "browserslist": "4.16.6",
"cheerio": "0.22.0", "cheerio": "0.22.0",
"clone": "2.1.2", "clone": "2.1.2",
"cookie": "0.4.1", "cookie": "0.4.1",
......
...@@ -10,6 +10,7 @@ import { ClientPagesLoaderOptions } from './webpack/loaders/next-client-pages-lo ...@@ -10,6 +10,7 @@ import { ClientPagesLoaderOptions } from './webpack/loaders/next-client-pages-lo
import { ServerlessLoaderQuery } from './webpack/loaders/next-serverless-loader' import { ServerlessLoaderQuery } from './webpack/loaders/next-serverless-loader'
import { LoadedEnvFiles } from '@next/env' import { LoadedEnvFiles } from '@next/env'
import { NextConfigComplete } from '../server/config-shared' import { NextConfigComplete } from '../server/config-shared'
import type webpack5 from 'webpack5'
type PagesMapping = { type PagesMapping = {
[page: string]: string [page: string]: string
...@@ -62,21 +63,9 @@ export function createPagesMapping( ...@@ -62,21 +63,9 @@ export function createPagesMapping(
return pages return pages
} }
export type WebpackEntrypoints = {
[bundle: string]:
| string
| string[]
| {
import: string | string[]
dependOn?: string | string[]
publicPath?: string
runtime?: string
}
}
type Entrypoints = { type Entrypoints = {
client: WebpackEntrypoints client: webpack5.EntryObject
server: WebpackEntrypoints server: webpack5.EntryObject
} }
export function createEntrypoints( export function createEntrypoints(
...@@ -87,8 +76,8 @@ export function createEntrypoints( ...@@ -87,8 +76,8 @@ export function createEntrypoints(
config: NextConfigComplete, config: NextConfigComplete,
loadedEnvFiles: LoadedEnvFiles loadedEnvFiles: LoadedEnvFiles
): Entrypoints { ): Entrypoints {
const client: WebpackEntrypoints = {} const client: webpack5.EntryObject = {}
const server: WebpackEntrypoints = {} const server: webpack5.EntryObject = {}
const hasRuntimeConfig = const hasRuntimeConfig =
Object.keys(config.publicRuntimeConfig).length > 0 || Object.keys(config.publicRuntimeConfig).length > 0 ||
......
...@@ -840,22 +840,25 @@ export async function isPageStatic( ...@@ -840,22 +840,25 @@ export async function isPageStatic(
try { try {
require('../shared/lib/runtime-config').setConfig(runtimeEnvConfig) require('../shared/lib/runtime-config').setConfig(runtimeEnvConfig)
setHttpAgentOptions(httpAgentOptions) setHttpAgentOptions(httpAgentOptions)
const components = await loadComponents(distDir, page, serverless) const mod = await loadComponents(distDir, page, serverless)
const mod = components.ComponentMod const Comp = mod.Component
const Comp = mod.default || mod
if (!Comp || !isValidElementType(Comp) || typeof Comp === 'string') { if (!Comp || !isValidElementType(Comp) || typeof Comp === 'string') {
throw new Error('INVALID_DEFAULT_EXPORT') throw new Error('INVALID_DEFAULT_EXPORT')
} }
const hasGetInitialProps = !!(Comp as any).getInitialProps const hasGetInitialProps = !!(Comp as any).getInitialProps
const hasStaticProps = !!(await mod.getStaticProps) const hasStaticProps = !!mod.getStaticProps
const hasStaticPaths = !!(await mod.getStaticPaths) const hasStaticPaths = !!mod.getStaticPaths
const hasServerProps = !!(await mod.getServerSideProps) const hasServerProps = !!mod.getServerSideProps
const hasLegacyServerProps = !!(await mod.unstable_getServerProps) const hasLegacyServerProps = !!(await mod.ComponentMod
const hasLegacyStaticProps = !!(await mod.unstable_getStaticProps) .unstable_getServerProps)
const hasLegacyStaticPaths = !!(await mod.unstable_getStaticPaths) const hasLegacyStaticProps = !!(await mod.ComponentMod
const hasLegacyStaticParams = !!(await mod.unstable_getStaticParams) .unstable_getStaticProps)
const hasLegacyStaticPaths = !!(await mod.ComponentMod
.unstable_getStaticPaths)
const hasLegacyStaticParams = !!(await mod.ComponentMod
.unstable_getStaticParams)
if (hasLegacyStaticParams) { if (hasLegacyStaticParams) {
throw new Error( throw new Error(
...@@ -921,14 +924,14 @@ export async function isPageStatic( ...@@ -921,14 +924,14 @@ export async function isPageStatic(
encodedPaths: encodedPrerenderRoutes, encodedPaths: encodedPrerenderRoutes,
} = await buildStaticPaths( } = await buildStaticPaths(
page, page,
mod.getStaticPaths, mod.getStaticPaths!,
locales, locales,
defaultLocale defaultLocale
)) ))
} }
const isNextImageImported = (global as any).__NEXT_IMAGE_IMPORTED const isNextImageImported = (global as any).__NEXT_IMAGE_IMPORTED
const config: PageConfig = mod.config || {} const config: PageConfig = mod.pageConfig
return { return {
isStatic: !hasStaticProps && !hasGetInitialProps && !hasServerProps, isStatic: !hasStaticProps && !hasGetInitialProps && !hasServerProps,
isHybridAmp: config.amp === 'hybrid', isHybridAmp: config.amp === 'hybrid',
......
...@@ -5,6 +5,7 @@ import { readFileSync } from 'fs' ...@@ -5,6 +5,7 @@ import { readFileSync } from 'fs'
import { codeFrameColumns } from 'next/dist/compiled/babel/code-frame' import { codeFrameColumns } from 'next/dist/compiled/babel/code-frame'
import semver from 'next/dist/compiled/semver' import semver from 'next/dist/compiled/semver'
import { isWebpack5, webpack } from 'next/dist/compiled/webpack/webpack' import { isWebpack5, webpack } from 'next/dist/compiled/webpack/webpack'
import type webpack5 from 'webpack5'
import path, { join as pathJoin, relative as relativePath } from 'path' import path, { join as pathJoin, relative as relativePath } from 'path'
import { import {
DOT_NEXT_ALIAS, DOT_NEXT_ALIAS,
...@@ -28,7 +29,7 @@ import { ...@@ -28,7 +29,7 @@ import {
} from '../shared/lib/constants' } from '../shared/lib/constants'
import { execOnce } from '../shared/lib/utils' import { execOnce } from '../shared/lib/utils'
import { NextConfigComplete } from '../server/config-shared' import { NextConfigComplete } from '../server/config-shared'
import { finalizeEntrypoint, WebpackEntrypoints } from './entries' import { finalizeEntrypoint } from './entries'
import * as Log from './output/log' import * as Log from './output/log'
import { build as buildConfiguration } from './webpack/config' import { build as buildConfiguration } from './webpack/config'
import { __overrideCssConfiguration } from './webpack/config/blocks/css/overrideCssConfiguration' import { __overrideCssConfiguration } from './webpack/config/blocks/css/overrideCssConfiguration'
...@@ -224,7 +225,7 @@ export default async function getBaseWebpackConfig( ...@@ -224,7 +225,7 @@ export default async function getBaseWebpackConfig(
pagesDir: string pagesDir: string
target?: string target?: string
reactProductionProfiling?: boolean reactProductionProfiling?: boolean
entrypoints: WebpackEntrypoints entrypoints: webpack5.EntryObject
rewrites: CustomRoutes['rewrites'] rewrites: CustomRoutes['rewrites']
isDevFallback?: boolean isDevFallback?: boolean
runWebpackSpan: Span runWebpackSpan: Span
...@@ -1379,16 +1380,21 @@ export default async function getBaseWebpackConfig( ...@@ -1379,16 +1380,21 @@ export default async function getBaseWebpackConfig(
// futureEmitAssets is on by default in webpack 5 // futureEmitAssets is on by default in webpack 5
delete webpackConfig.output?.futureEmitAssets delete webpackConfig.output?.futureEmitAssets
webpackConfig.experiments = { // webpack 5 no longer polyfills Node.js modules:
if (webpackConfig.node) delete webpackConfig.node.setImmediate
const webpack5Config = webpackConfig as webpack5.Configuration
webpack5Config.experiments = {
layers: true, layers: true,
} }
webpackConfig.module!.parser = { webpack5Config.module!.parser = {
javascript: { javascript: {
url: 'relative', url: 'relative',
}, },
} }
webpackConfig.module!.generator = { webpack5Config.module!.generator = {
asset: { asset: {
filename: 'static/media/[name].[hash:8][ext]', filename: 'static/media/[name].[hash:8][ext]',
}, },
...@@ -1396,24 +1402,19 @@ export default async function getBaseWebpackConfig( ...@@ -1396,24 +1402,19 @@ export default async function getBaseWebpackConfig(
if (isServer && dev) { if (isServer && dev) {
// Enable building of client compilation before server compilation in development // Enable building of client compilation before server compilation in development
// @ts-ignore dependencies exists webpack5Config.dependencies = ['client']
webpackConfig.dependencies = ['client']
} }
// webpack 5 no longer polyfills Node.js modules:
if (webpackConfig.node) delete webpackConfig.node.setImmediate
// Due to bundling of webpack the default values can't be correctly detected // Due to bundling of webpack the default values can't be correctly detected
// This restores the webpack defaults // This restores the webpack defaults
// @ts-ignore webpack 5 webpack5Config.snapshot = {}
webpackConfig.snapshot = {}
if (process.versions.pnp === '3') { if (process.versions.pnp === '3') {
const match = const match =
/^(.+?)[\\/]cache[\\/]jest-worker-npm-[^\\/]+\.zip[\\/]node_modules[\\/]/.exec( /^(.+?)[\\/]cache[\\/]jest-worker-npm-[^\\/]+\.zip[\\/]node_modules[\\/]/.exec(
require.resolve('jest-worker') require.resolve('jest-worker')
) )
if (match) { if (match) {
// @ts-ignore webpack 5 webpack5Config.snapshot.managedPaths = [
webpackConfig.snapshot.managedPaths = [
path.resolve(match[1], 'unplugged'), path.resolve(match[1], 'unplugged'),
] ]
} }
...@@ -1422,8 +1423,7 @@ export default async function getBaseWebpackConfig( ...@@ -1422,8 +1423,7 @@ export default async function getBaseWebpackConfig(
require.resolve('jest-worker') require.resolve('jest-worker')
) )
if (match) { if (match) {
// @ts-ignore webpack 5 webpack5Config.snapshot.managedPaths = [match[1]]
webpackConfig.snapshot.managedPaths = [match[1]]
} }
} }
if (process.versions.pnp === '1') { if (process.versions.pnp === '1') {
...@@ -1432,8 +1432,7 @@ export default async function getBaseWebpackConfig( ...@@ -1432,8 +1432,7 @@ export default async function getBaseWebpackConfig(
require.resolve('jest-worker') require.resolve('jest-worker')
) )
if (match) { if (match) {
// @ts-ignore webpack 5 webpack5Config.snapshot.immutablePaths = [match[1]]
webpackConfig.snapshot.immutablePaths = [match[1]]
} }
} else if (process.versions.pnp === '3') { } else if (process.versions.pnp === '3') {
const match = const match =
...@@ -1441,17 +1440,16 @@ export default async function getBaseWebpackConfig( ...@@ -1441,17 +1440,16 @@ export default async function getBaseWebpackConfig(
require.resolve('jest-worker') require.resolve('jest-worker')
) )
if (match) { if (match) {
// @ts-ignore webpack 5 webpack5Config.snapshot.immutablePaths = [match[1]]
webpackConfig.snapshot.immutablePaths = [match[1]]
} }
} }
if (dev) { if (dev) {
if (!webpackConfig.optimization) { if (!webpack5Config.optimization) {
webpackConfig.optimization = {} webpack5Config.optimization = {}
} }
webpackConfig.optimization.providedExports = false webpack5Config.optimization.providedExports = false
webpackConfig.optimization.usedExports = false webpack5Config.optimization.usedExports = false
} }
const configVars = JSON.stringify({ const configVars = JSON.stringify({
...@@ -1496,7 +1494,7 @@ export default async function getBaseWebpackConfig( ...@@ -1496,7 +1494,7 @@ export default async function getBaseWebpackConfig(
} }
} }
webpackConfig.cache = cache webpack5Config.cache = cache
if (process.env.NEXT_WEBPACK_LOGGING) { if (process.env.NEXT_WEBPACK_LOGGING) {
const logInfra = const logInfra =
...@@ -1508,8 +1506,7 @@ export default async function getBaseWebpackConfig( ...@@ -1508,8 +1506,7 @@ export default async function getBaseWebpackConfig(
const logDefault = !logInfra && !logProfileClient && !logProfileServer const logDefault = !logInfra && !logProfileClient && !logProfileServer
if (logDefault || logInfra) { if (logDefault || logInfra) {
// @ts-ignore TODO: remove ignore when webpack 5 is stable webpack5Config.infrastructureLogging = {
webpackConfig.infrastructureLogging = {
level: 'verbose', level: 'verbose',
debug: /FileSystemInfo/, debug: /FileSystemInfo/,
} }
...@@ -1520,12 +1517,11 @@ export default async function getBaseWebpackConfig( ...@@ -1520,12 +1517,11 @@ export default async function getBaseWebpackConfig(
(logProfileClient && !isServer) || (logProfileClient && !isServer) ||
(logProfileServer && isServer) (logProfileServer && isServer)
) { ) {
webpackConfig.plugins!.push((compiler: webpack.Compiler) => { webpack5Config.plugins!.push((compiler: webpack5.Compiler) => {
compiler.hooks.done.tap('next-webpack-logging', (stats) => { compiler.hooks.done.tap('next-webpack-logging', (stats) => {
console.log( console.log(
stats.toString({ stats.toString({
colors: true, colors: true,
// @ts-ignore TODO: remove ignore when webpack 5 is stable
logging: logDefault ? 'log' : 'verbose', logging: logDefault ? 'log' : 'verbose',
}) })
) )
...@@ -1534,13 +1530,14 @@ export default async function getBaseWebpackConfig( ...@@ -1534,13 +1530,14 @@ export default async function getBaseWebpackConfig(
} }
if ((logProfileClient && !isServer) || (logProfileServer && isServer)) { if ((logProfileClient && !isServer) || (logProfileServer && isServer)) {
webpackConfig.plugins!.push( const ProgressPlugin =
new webpack.ProgressPlugin({ webpack.ProgressPlugin as unknown as typeof webpack5.ProgressPlugin
// @ts-ignore TODO: remove ignore when webpack 5 is stable webpack5Config.plugins!.push(
new ProgressPlugin({
profile: true, profile: true,
}) })
) )
webpackConfig.profile = true webpack5Config.profile = true
} }
} }
} }
...@@ -1897,7 +1894,7 @@ export default async function getBaseWebpackConfig( ...@@ -1897,7 +1894,7 @@ export default async function getBaseWebpackConfig(
const originalEntry: any = webpackConfig.entry const originalEntry: any = webpackConfig.entry
if (typeof originalEntry !== 'undefined') { if (typeof originalEntry !== 'undefined') {
const updatedEntry = async () => { const updatedEntry = async () => {
const entry: WebpackEntrypoints = const entry: webpack5.EntryObject =
typeof originalEntry === 'function' typeof originalEntry === 'function'
? await originalEntry() ? await originalEntry()
: originalEntry : originalEntry
......
...@@ -4,7 +4,10 @@ import { Transform, TransformCallback } from 'stream' ...@@ -4,7 +4,10 @@ import { Transform, TransformCallback } from 'stream'
// @ts-ignore no types package // @ts-ignore no types package
import bfj from 'next/dist/compiled/bfj' import bfj from 'next/dist/compiled/bfj'
import { spans } from './profiling-plugin' import { spans } from './profiling-plugin'
import { webpack } from 'next/dist/compiled/webpack/webpack' import { isWebpack5 } from 'next/dist/compiled/webpack/webpack'
import type webpack from 'webpack'
import type webpack4 from 'webpack4'
import type webpack5 from 'webpack5'
const STATS_VERSION = 0 const STATS_VERSION = 0
...@@ -121,8 +124,7 @@ export default class BuildStatsPlugin { ...@@ -121,8 +124,7 @@ export default class BuildStatsPlugin {
const writeStatsSpan = compilationSpan!.traceChild('NextJsBuildStats') const writeStatsSpan = compilationSpan!.traceChild('NextJsBuildStats')
await writeStatsSpan.traceAsyncFn(() => { await writeStatsSpan.traceAsyncFn(() => {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
const statsJson = reduceSize( const baseOptions = {
stats.toJson({
all: false, all: false,
cached: true, cached: true,
reasons: true, reasons: true,
...@@ -133,9 +135,18 @@ export default class BuildStatsPlugin { ...@@ -133,9 +135,18 @@ export default class BuildStatsPlugin {
maxModules: Infinity, maxModules: Infinity,
chunkModules: true, chunkModules: true,
modules: true, modules: true,
// @ts-ignore this option exists }
const statsJson = reduceSize(
isWebpack5
? (stats as webpack5.Stats).toJson({
...baseOptions,
modulesSpace: Infinity,
ids: true, ids: true,
}) })
: (stats as webpack4.Stats).toJson({
...baseOptions,
maxModules: Infinity,
})
) )
const fileStream = fs.createWriteStream( const fileStream = fs.createWriteStream(
path.join(this.distDir, 'next-stats.json'), path.join(this.distDir, 'next-stats.json'),
......
import { webpack, isWebpack5 } from 'next/dist/compiled/webpack/webpack' import { NormalModule, isWebpack5 } from 'next/dist/compiled/webpack/webpack'
import { Span } from '../../../trace' import { Span } from '../../../trace'
import type webpack from 'webpack'
const pluginName = 'ProfilingPlugin' const pluginName = 'ProfilingPlugin'
export const spans = new WeakMap< export const spans = new WeakMap<webpack.Compilation | webpack.Compiler, Span>()
webpack.compilation.Compilation | webpack.Compiler,
Span
>()
const moduleSpansByCompilation = new WeakMap< const moduleSpansByCompilation = new WeakMap<
webpack.compilation.Compilation, webpack.Compilation,
WeakMap<webpack.Module, Span> WeakMap<webpack.Module, Span>
>() >()
export const webpackInvalidSpans = new WeakMap<any, Span>() export const webpackInvalidSpans = new WeakMap<any, Span>()
...@@ -15,7 +13,7 @@ export const webpackInvalidSpans = new WeakMap<any, Span>() ...@@ -15,7 +13,7 @@ export const webpackInvalidSpans = new WeakMap<any, Span>()
function getNormalModuleLoaderHook(compilation: any) { function getNormalModuleLoaderHook(compilation: any) {
if (isWebpack5) { if (isWebpack5) {
// @ts-ignore TODO: Remove ignore when webpack 5 is stable // @ts-ignore TODO: Remove ignore when webpack 5 is stable
return webpack.NormalModule.getCompilationHooks(compilation).loader return NormalModule.getCompilationHooks(compilation).loader
} }
return compilation.hooks.normalModuleLoader return compilation.hooks.normalModuleLoader
......
...@@ -33,6 +33,78 @@ const hookPropertyMap = new Map( ...@@ -33,6 +33,78 @@ const hookPropertyMap = new Map(
'webpack/lib/node/NodeTargetPlugin.js', 'webpack/lib/node/NodeTargetPlugin.js',
'next/dist/compiled/webpack/NodeTargetPlugin', 'next/dist/compiled/webpack/NodeTargetPlugin',
], ],
[
'webpack/lib/node/NodeTemplatePlugin',
'next/dist/compiled/webpack/NodeTemplatePlugin',
],
[
'webpack/lib/node/NodeTemplatePlugin.js',
'next/dist/compiled/webpack/NodeTemplatePlugin',
],
[
'webpack/lib/LibraryTemplatePlugin',
'next/dist/compiled/webpack/LibraryTemplatePlugin',
],
[
'webpack/lib/LibraryTemplatePlugin.js',
'next/dist/compiled/webpack/LibraryTemplatePlugin',
],
[
'webpack/lib/SingleEntryPlugin',
'next/dist/compiled/webpack/SingleEntryPlugin',
],
[
'webpack/lib/SingleEntryPlugin.js',
'next/dist/compiled/webpack/SingleEntryPlugin',
],
[
'webpack/lib/optimize/LimitChunkCountPlugin',
'next/dist/compiled/webpack/LimitChunkCountPlugin',
],
[
'webpack/lib/optimize/LimitChunkCountPlugin.js',
'next/dist/compiled/webpack/LimitChunkCountPlugin',
],
[
'webpack/lib/webworker/WebWorkerTemplatePlugin',
'next/dist/compiled/webpack/WebWorkerTemplatePlugin',
],
[
'webpack/lib/webworker/WebWorkerTemplatePlugin.js',
'next/dist/compiled/webpack/WebWorkerTemplatePlugin',
],
[
'webpack/lib/ExternalsPlugin',
'next/dist/compiled/webpack/ExternalsPlugin',
],
[
'webpack/lib/ExternalsPlugin.js',
'next/dist/compiled/webpack/ExternalsPlugin',
],
[
'webpack/lib/web/FetchCompileWasmTemplatePlugin',
'next/dist/compiled/webpack/FetchCompileWasmTemplatePlugin',
],
[
'webpack/lib/web/FetchCompileWasmTemplatePlugin.js',
'next/dist/compiled/webpack/FetchCompileWasmTemplatePlugin',
],
[
'webpack/lib/web/FetchCompileWasmPlugin',
'next/dist/compiled/webpack/FetchCompileWasmPlugin',
],
[
'webpack/lib/web/FetchCompileWasmPlugin.js',
'next/dist/compiled/webpack/FetchCompileWasmPlugin',
],
[
'webpack/lib/web/FetchCompileAsyncWasmPlugin',
'next/dist/compiled/webpack/FetchCompileAsyncWasmPlugin',
],
[
'webpack/lib/web/FetchCompileAsyncWasmPlugin.js',
'next/dist/compiled/webpack/FetchCompileAsyncWasmPlugin',
],
[ [
'webpack/lib/ModuleFilenameHelpers', 'webpack/lib/ModuleFilenameHelpers',
'next/dist/compiled/webpack/ModuleFilenameHelpers', 'next/dist/compiled/webpack/ModuleFilenameHelpers',
...@@ -63,3 +135,6 @@ mod._resolveFilename = function ( ...@@ -63,3 +135,6 @@ mod._resolveFilename = function (
if (hookResolved) request = hookResolved if (hookResolved) request = hookResolved
return resolveFilename.call(mod, request, parent, isMain, options) return resolveFilename.call(mod, request, parent, isMain, options)
} }
// Flag as module for typescript
export {}
{
"dependencies": {
"schema-utils3": "npm:schema-utils@3.0.0",
"webpack-sources3": "npm:webpack-sources@3.2.0",
"webpack5": "npm:webpack@5.53.0"
},
"resolutions": {
"browserslist": "4.16.6",
"caniuse-lite": "1.0.30001228"
}
}
...@@ -2,23 +2,28 @@ ...@@ -2,23 +2,28 @@
module.exports = function () { module.exports = function () {
return { return {
BasicEvaluatedExpression: require('webpack/lib/BasicEvaluatedExpression'), BasicEvaluatedExpression: require('webpack4/lib/BasicEvaluatedExpression'),
NodeEnvironmentPlugin: require('webpack/lib/node/NodeEnvironmentPlugin'), NodeEnvironmentPlugin: require('webpack4/lib/node/NodeEnvironmentPlugin'),
NodeTargetPlugin: require('webpack/lib/node/NodeTargetPlugin'), NodeTargetPlugin: require('webpack4/lib/node/NodeTargetPlugin'),
ModuleFilenameHelpers: require('webpack/lib/ModuleFilenameHelpers'), NodeTemplatePlugin: require('webpack4/lib/node/NodeTemplatePlugin'),
GraphHelpers: require('webpack/lib/GraphHelpers'), ModuleFilenameHelpers: require('webpack4/lib/ModuleFilenameHelpers'),
Module: require('webpack/lib/Module'), GraphHelpers: require('webpack4/lib/GraphHelpers'),
NormalModule: require('webpack/lib/NormalModule'), Module: require('webpack4/lib/Module'),
Dependency: require('webpack/lib/Dependency'), NormalModule: require('webpack4/lib/NormalModule'),
LibraryTemplatePlugin: require('webpack/lib/LibraryTemplatePlugin'), Dependency: require('webpack4/lib/Dependency'),
SingleEntryPlugin: require('webpack/lib/SingleEntryPlugin'), LibraryTemplatePlugin: require('webpack4/lib/LibraryTemplatePlugin'),
node: require('webpack').node, SingleEntryPlugin: require('webpack4/lib/SingleEntryPlugin'),
util: require('webpack').util, FetchCompileWasmTemplatePlugin: require('webpack4/lib/web/FetchCompileWasmTemplatePlugin'),
optimize: require('webpack').optimize, LimitChunkCountPlugin: require('webpack4/lib/optimize/LimitChunkCountPlugin'),
WebWorkerTemplatePlugin: require('webpack4/lib/webworker/WebWorkerTemplatePlugin'),
ExternalsPlugin: require('webpack4/lib/ExternalsPlugin'),
node: require('webpack4').node,
util: require('webpack4').util,
optimize: require('webpack4').optimize,
sources: require('webpack-sources'), sources: require('webpack-sources'),
webpack: require('webpack'), webpack: require('webpack4'),
package: { package: {
version: require('webpack/package.json').version, version: require('webpack4/package.json').version,
}, },
} }
} }
...@@ -5,9 +5,20 @@ module.exports = function () { ...@@ -5,9 +5,20 @@ module.exports = function () {
BasicEvaluatedExpression: require('webpack5/lib/javascript/BasicEvaluatedExpression'), BasicEvaluatedExpression: require('webpack5/lib/javascript/BasicEvaluatedExpression'),
ModuleFilenameHelpers: require('webpack5/lib/ModuleFilenameHelpers'), ModuleFilenameHelpers: require('webpack5/lib/ModuleFilenameHelpers'),
NodeTargetPlugin: require('webpack5/lib/node/NodeTargetPlugin'), NodeTargetPlugin: require('webpack5/lib/node/NodeTargetPlugin'),
NodeTemplatePlugin: require('webpack5/lib/node/NodeTemplatePlugin'),
LibraryTemplatePlugin: require('webpack5/lib/LibraryTemplatePlugin'),
LimitChunkCountPlugin: require('webpack5/lib/optimize/LimitChunkCountPlugin'),
WebWorkerTemplatePlugin: require('webpack5/lib/webworker/WebWorkerTemplatePlugin'),
ExternalsPlugin: require('webpack5/lib/ExternalsPlugin'),
SingleEntryPlugin: require('webpack5/lib/SingleEntryPlugin'),
FetchCompileAsyncWasmPlugin: require('webpack5/lib/web/FetchCompileAsyncWasmPlugin'),
FetchCompileWasmPlugin: require('webpack5/lib/web/FetchCompileWasmPlugin'),
StringXor: require('webpack5/lib/util/StringXor'), StringXor: require('webpack5/lib/util/StringXor'),
NormalModule: require('webpack/lib/NormalModule'), NormalModule: require('webpack5/lib/NormalModule'),
sources: require('webpack5').sources, sources: require('webpack5').sources,
webpack: require('webpack5'), webpack: require('webpack5'),
package: {
version: require('webpack5/package.json').version,
},
} }
} }
module.exports = require('./webpack.js').ExternalsPlugin
module.exports = require('./webpack.js').FetchCompileAsyncWasmPlugin
module.exports = require('./webpack.js').FetchCompileWasmPlugin
module.exports = require('./webpack.js').FetchCompileWasmTemplatePlugin
module.exports = require('./webpack.js').LibraryTemplatePlugin
module.exports = require('./webpack.js').LimitChunkCountPlugin
module.exports = require('./webpack.js').NodeTemplatePlugin
module.exports = require('./webpack.js').SingleEntryPlugin
module.exports = require('./webpack.js').WebWorkerTemplatePlugin
This diff is collapsed.
module.exports=(()=>{"use strict";var e={764:e=>{e.exports=JSON.parse('{"additionalProperties":true,"properties":{"name":{"description":"The filename template for the target file(s) (https://github.com/webpack-contrib/file-loader#name).","anyOf":[{"type":"string"},{"instanceof":"Function"}]},"outputPath":{"description":"A filesystem path where the target file(s) will be placed (https://github.com/webpack-contrib/file-loader#outputpath).","anyOf":[{"type":"string"},{"instanceof":"Function"}]},"publicPath":{"description":"A custom public path for the target file(s) (https://github.com/webpack-contrib/file-loader#publicpath).","anyOf":[{"type":"string"},{"instanceof":"Function"}]},"postTransformPublicPath":{"description":"A custom transformation function for post-processing the publicPath (https://github.com/webpack-contrib/file-loader#posttransformpublicpath).","instanceof":"Function"},"context":{"description":"A custom file context (https://github.com/webpack-contrib/file-loader#context).","type":"string"},"emitFile":{"description":"Enables/Disables emit files (https://github.com/webpack-contrib/file-loader#emitfile).","type":"boolean"},"regExp":{"description":"A Regular Expression to one or many parts of the target file path. The capture groups can be reused in the name property using [N] placeholder (https://github.com/webpack-contrib/file-loader#regexp).","anyOf":[{"type":"string"},{"instanceof":"RegExp"}]},"esModule":{"description":"By default, file-loader generates JS modules that use the ES modules syntax.","type":"boolean"}},"type":"object"}')},467:(e,t,i)=>{const r=i(206);e.exports=r.default;e.exports.raw=r.raw},206:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:true});t.default=loader;t.raw=void 0;var r=_interopRequireDefault(i(622));var o=_interopRequireDefault(i(443));var a=_interopRequireDefault(i(225));var n=_interopRequireDefault(i(764));function _interopRequireDefault(e){return e&&e.__esModule?e:{default:e}}function loader(e){const t=o.default.getOptions(this);(0,a.default)(n.default,t,{name:"File Loader",baseDataPath:"options"});const i=t.context||this.rootContext;const s=o.default.interpolateName(this,t.name||"[contenthash].[ext]",{context:i,content:e,regExp:t.regExp});let p=s;if(t.outputPath){if(typeof t.outputPath==="function"){p=t.outputPath(s,this.resourcePath,i)}else{p=r.default.posix.join(t.outputPath,s)}}let u=`__webpack_public_path__ + ${JSON.stringify(p)}`;if(t.publicPath){if(typeof t.publicPath==="function"){u=t.publicPath(s,this.resourcePath,i)}else{u=`${t.publicPath.endsWith("/")?t.publicPath:`${t.publicPath}/`}${s}`}u=JSON.stringify(u)}if(t.postTransformPublicPath){u=t.postTransformPublicPath(u)}if(typeof t.emitFile==="undefined"||t.emitFile){this.emitFile(p,e)}const l=typeof t.esModule!=="undefined"?t.esModule:true;return`${l?"export default":"module.exports ="} ${u};`}const s=true;t.raw=s},443:e=>{e.exports=require("next/dist/compiled/loader-utils")},225:e=>{e.exports=require("next/dist/compiled/schema-utils")},622:e=>{e.exports=require("path")}};var t={};function __nccwpck_require__(i){if(t[i]){return t[i].exports}var r=t[i]={exports:{}};var o=true;try{e[i](r,r.exports,__nccwpck_require__);o=false}finally{if(o)delete t[i]}return r.exports}__nccwpck_require__.ab=__dirname+"/";return __nccwpck_require__(467)})(); module.exports=(()=>{"use strict";var e={764:e=>{e.exports=JSON.parse('{"additionalProperties":true,"properties":{"name":{"description":"The filename template for the target file(s) (https://github.com/webpack-contrib/file-loader#name).","anyOf":[{"type":"string"},{"instanceof":"Function"}]},"outputPath":{"description":"A filesystem path where the target file(s) will be placed (https://github.com/webpack-contrib/file-loader#outputpath).","anyOf":[{"type":"string"},{"instanceof":"Function"}]},"publicPath":{"description":"A custom public path for the target file(s) (https://github.com/webpack-contrib/file-loader#publicpath).","anyOf":[{"type":"string"},{"instanceof":"Function"}]},"postTransformPublicPath":{"description":"A custom transformation function for post-processing the publicPath (https://github.com/webpack-contrib/file-loader#posttransformpublicpath).","instanceof":"Function"},"context":{"description":"A custom file context (https://github.com/webpack-contrib/file-loader#context).","type":"string"},"emitFile":{"description":"Enables/Disables emit files (https://github.com/webpack-contrib/file-loader#emitfile).","type":"boolean"},"regExp":{"description":"A Regular Expression to one or many parts of the target file path. The capture groups can be reused in the name property using [N] placeholder (https://github.com/webpack-contrib/file-loader#regexp).","anyOf":[{"type":"string"},{"instanceof":"RegExp"}]},"esModule":{"description":"By default, file-loader generates JS modules that use the ES modules syntax.","type":"boolean"}},"type":"object"}')},467:(e,t,i)=>{const r=i(206);e.exports=r.default;e.exports.raw=r.raw},206:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:true});t.default=loader;t.raw=void 0;var r=_interopRequireDefault(i(622));var o=_interopRequireDefault(i(443));var a=_interopRequireDefault(i(99));var n=_interopRequireDefault(i(764));function _interopRequireDefault(e){return e&&e.__esModule?e:{default:e}}function loader(e){const t=o.default.getOptions(this);(0,a.default)(n.default,t,{name:"File Loader",baseDataPath:"options"});const i=t.context||this.rootContext;const s=o.default.interpolateName(this,t.name||"[contenthash].[ext]",{context:i,content:e,regExp:t.regExp});let p=s;if(t.outputPath){if(typeof t.outputPath==="function"){p=t.outputPath(s,this.resourcePath,i)}else{p=r.default.posix.join(t.outputPath,s)}}let u=`__webpack_public_path__ + ${JSON.stringify(p)}`;if(t.publicPath){if(typeof t.publicPath==="function"){u=t.publicPath(s,this.resourcePath,i)}else{u=`${t.publicPath.endsWith("/")?t.publicPath:`${t.publicPath}/`}${s}`}u=JSON.stringify(u)}if(t.postTransformPublicPath){u=t.postTransformPublicPath(u)}if(typeof t.emitFile==="undefined"||t.emitFile){this.emitFile(p,e)}const l=typeof t.esModule!=="undefined"?t.esModule:true;return`${l?"export default":"module.exports ="} ${u};`}const s=true;t.raw=s},443:e=>{e.exports=require("next/dist/compiled/loader-utils")},99:e=>{e.exports=require("next/dist/compiled/schema-utils2")},622:e=>{e.exports=require("path")}};var t={};function __nccwpck_require__(i){if(t[i]){return t[i].exports}var r=t[i]={exports:{}};var o=true;try{e[i](r,r.exports,__nccwpck_require__);o=false}finally{if(o)delete t[i]}return r.exports}__nccwpck_require__.ab=__dirname+"/";return __nccwpck_require__(467)})();
\ No newline at end of file \ No newline at end of file
This source diff could not be displayed because it is too large. You can view the blob instead.
module.exports = require('./webpack.js').ExternalsPlugin
module.exports = require('./webpack.js').FetchCompileAsyncWasmPlugin
module.exports = require('./webpack.js').FetchCompileWasmPlugin
module.exports = require('./webpack.js').FetchCompileWasmTemplatePlugin
module.exports = require('./webpack.js').LibraryTemplatePlugin
module.exports = require('./webpack.js').LimitChunkCountPlugin
module.exports = require('./webpack.js').NodeTemplatePlugin
module.exports = require('./webpack.js').SingleEntryPlugin
module.exports = require('./webpack.js').WebWorkerTemplatePlugin
...@@ -2,7 +2,7 @@ module.exports = ...@@ -2,7 +2,7 @@ module.exports =
/******/ (function() { // webpackBootstrap /******/ (function() { // webpackBootstrap
/******/ var __webpack_modules__ = ({ /******/ var __webpack_modules__ = ({
/***/ 441: /***/ 950:
/***/ (function(module) { /***/ (function(module) {
module.exports = function() { module.exports = function() {
...@@ -50,6 +50,6 @@ module.exports = function() { ...@@ -50,6 +50,6 @@ module.exports = function() {
/******/ // module exports must be returned from runtime so entry inlining is disabled /******/ // module exports must be returned from runtime so entry inlining is disabled
/******/ // startup /******/ // startup
/******/ // Load entry module and return exports /******/ // Load entry module and return exports
/******/ return __nccwpck_require__(441); /******/ return __nccwpck_require__(950);
/******/ })() /******/ })()
; ;
\ No newline at end of file
...@@ -2,7 +2,7 @@ module.exports = ...@@ -2,7 +2,7 @@ module.exports =
/******/ (function() { // webpackBootstrap /******/ (function() { // webpackBootstrap
/******/ var __webpack_modules__ = ({ /******/ var __webpack_modules__ = ({
/***/ 929: /***/ 560:
/***/ (function(module) { /***/ (function(module) {
/* globals __webpack_amd_options__ */ /* globals __webpack_amd_options__ */
...@@ -49,6 +49,6 @@ module.exports = __webpack_amd_options__; ...@@ -49,6 +49,6 @@ module.exports = __webpack_amd_options__;
/******/ // module exports must be returned from runtime so entry inlining is disabled /******/ // module exports must be returned from runtime so entry inlining is disabled
/******/ // startup /******/ // startup
/******/ // Load entry module and return exports /******/ // Load entry module and return exports
/******/ return __nccwpck_require__(929); /******/ return __nccwpck_require__(560);
/******/ })() /******/ })()
; ;
\ No newline at end of file
This diff is collapsed.
This diff is collapsed.
...@@ -2,7 +2,7 @@ module.exports = ...@@ -2,7 +2,7 @@ module.exports =
/******/ (function() { // webpackBootstrap /******/ (function() { // webpackBootstrap
/******/ var __webpack_modules__ = ({ /******/ var __webpack_modules__ = ({
/***/ 149: /***/ 868:
/***/ (function(module) { /***/ (function(module) {
var g; var g;
...@@ -67,6 +67,6 @@ module.exports = g; ...@@ -67,6 +67,6 @@ module.exports = g;
/******/ // module exports must be returned from runtime so entry inlining is disabled /******/ // module exports must be returned from runtime so entry inlining is disabled
/******/ // startup /******/ // startup
/******/ // Load entry module and return exports /******/ // Load entry module and return exports
/******/ return __nccwpck_require__(149); /******/ return __nccwpck_require__(868);
/******/ })() /******/ })()
; ;
\ No newline at end of file
...@@ -2,7 +2,7 @@ module.exports = ...@@ -2,7 +2,7 @@ module.exports =
/******/ (function() { // webpackBootstrap /******/ (function() { // webpackBootstrap
/******/ var __webpack_modules__ = ({ /******/ var __webpack_modules__ = ({
/***/ 931: /***/ 460:
/***/ (function(module) { /***/ (function(module) {
module.exports = function(originalModule) { module.exports = function(originalModule) {
...@@ -71,6 +71,6 @@ module.exports = function(originalModule) { ...@@ -71,6 +71,6 @@ module.exports = function(originalModule) {
/******/ // module exports must be returned from runtime so entry inlining is disabled /******/ // module exports must be returned from runtime so entry inlining is disabled
/******/ // startup /******/ // startup
/******/ // Load entry module and return exports /******/ // Load entry module and return exports
/******/ return __nccwpck_require__(931); /******/ return __nccwpck_require__(460);
/******/ })() /******/ })()
; ;
\ No newline at end of file
...@@ -3,7 +3,7 @@ module.exports = ...@@ -3,7 +3,7 @@ module.exports =
/******/ "use strict"; /******/ "use strict";
/******/ var __webpack_modules__ = ({ /******/ var __webpack_modules__ = ({
/***/ 887: /***/ 668:
/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
var __resourceQuery = ""; var __resourceQuery = "";
...@@ -94,6 +94,6 @@ module.exports = require("http");; ...@@ -94,6 +94,6 @@ module.exports = require("http");;
/******/ // module exports must be returned from runtime so entry inlining is disabled /******/ // module exports must be returned from runtime so entry inlining is disabled
/******/ // startup /******/ // startup
/******/ // Load entry module and return exports /******/ // Load entry module and return exports
/******/ return __nccwpck_require__(887); /******/ return __nccwpck_require__(668);
/******/ })() /******/ })()
; ;
\ No newline at end of file
...@@ -3,7 +3,7 @@ module.exports = ...@@ -3,7 +3,7 @@ module.exports =
/******/ "use strict"; /******/ "use strict";
/******/ var __webpack_modules__ = ({ /******/ var __webpack_modules__ = ({
/***/ 949: /***/ 590:
/***/ (function(__unused_webpack_module, exports) { /***/ (function(__unused_webpack_module, exports) {
var __resourceQuery = ""; var __resourceQuery = "";
...@@ -123,6 +123,6 @@ exports.keepAlive = function (options) { ...@@ -123,6 +123,6 @@ exports.keepAlive = function (options) {
/******/ // module exports must be returned from runtime so entry inlining is disabled /******/ // module exports must be returned from runtime so entry inlining is disabled
/******/ // startup /******/ // startup
/******/ // Load entry module and return exports /******/ // Load entry module and return exports
/******/ return __nccwpck_require__(949); /******/ return __nccwpck_require__(590);
/******/ })() /******/ })()
; ;
\ No newline at end of file
...@@ -2,7 +2,7 @@ module.exports = ...@@ -2,7 +2,7 @@ module.exports =
/******/ (function() { // webpackBootstrap /******/ (function() { // webpackBootstrap
/******/ var __webpack_modules__ = ({ /******/ var __webpack_modules__ = ({
/***/ 880: /***/ 767:
/***/ (function(module) { /***/ (function(module) {
module.exports = function(module) { module.exports = function(module) {
...@@ -69,6 +69,6 @@ module.exports = function(module) { ...@@ -69,6 +69,6 @@ module.exports = function(module) {
/******/ // module exports must be returned from runtime so entry inlining is disabled /******/ // module exports must be returned from runtime so entry inlining is disabled
/******/ // startup /******/ // startup
/******/ // Load entry module and return exports /******/ // Load entry module and return exports
/******/ return __nccwpck_require__(880); /******/ return __nccwpck_require__(767);
/******/ })() /******/ })()
; ;
\ No newline at end of file
...@@ -2,7 +2,7 @@ module.exports = ...@@ -2,7 +2,7 @@ module.exports =
/******/ (function() { // webpackBootstrap /******/ (function() { // webpackBootstrap
/******/ var __webpack_modules__ = ({ /******/ var __webpack_modules__ = ({
/***/ 957: /***/ 20:
/***/ (function(module) { /***/ (function(module) {
// Provide a "System" global. // Provide a "System" global.
...@@ -54,6 +54,6 @@ module.exports = { ...@@ -54,6 +54,6 @@ module.exports = {
/******/ // module exports must be returned from runtime so entry inlining is disabled /******/ // module exports must be returned from runtime so entry inlining is disabled
/******/ // startup /******/ // startup
/******/ // Load entry module and return exports /******/ // Load entry module and return exports
/******/ return __nccwpck_require__(957); /******/ return __nccwpck_require__(20);
/******/ })() /******/ })()
; ;
\ No newline at end of file
...@@ -255,8 +255,10 @@ export default async function exportPage({ ...@@ -255,8 +255,10 @@ export default async function exportPage({
}, },
}) })
const { const {
Component: mod, Component,
ComponentMod,
getServerSideProps, getServerSideProps,
getStaticProps,
pageConfig, pageConfig,
} = await loadComponents(distDir, page, serverless) } = await loadComponents(distDir, page, serverless)
const ampState = { const ampState = {
...@@ -274,25 +276,22 @@ export default async function exportPage({ ...@@ -274,25 +276,22 @@ export default async function exportPage({
} }
// if it was auto-exported the HTML is loaded here // if it was auto-exported the HTML is loaded here
if (typeof mod === 'string') { if (typeof Component === 'string') {
renderResult = RenderResult.fromStatic(mod) renderResult = RenderResult.fromStatic(Component)
queryWithAutoExportWarn() queryWithAutoExportWarn()
} else { } else {
// for non-dynamic SSG pages we should have already // for non-dynamic SSG pages we should have already
// prerendered the file // prerendered the file
if (renderedDuringBuild((mod as ComponentModule).getStaticProps)) if (renderedDuringBuild(getStaticProps))
return { ...results, duration: Date.now() - start } return { ...results, duration: Date.now() - start }
if ( if (getStaticProps && !htmlFilepath.endsWith('.html')) {
(mod as ComponentModule).getStaticProps &&
!htmlFilepath.endsWith('.html')
) {
// make sure it ends with .html if the name contains a dot // make sure it ends with .html if the name contains a dot
htmlFilename += '.html' htmlFilename += '.html'
htmlFilepath += '.html' htmlFilepath += '.html'
} }
renderMethod = (mod as ComponentModule).renderReqToHTML renderMethod = (ComponentMod as ComponentModule).renderReqToHTML
const result = await renderMethod( const result = await renderMethod(
req, req,
res, res,
......
...@@ -183,8 +183,7 @@ ...@@ -183,8 +183,7 @@
"@types/send": "0.14.4", "@types/send": "0.14.4",
"@types/styled-jsx": "2.2.8", "@types/styled-jsx": "2.2.8",
"@types/text-table": "0.2.1", "@types/text-table": "0.2.1",
"@types/webpack": "5.28.0", "@types/webpack-sources1": "npm:@types/webpack-sources@0.1.5",
"@types/webpack-sources": "0.1.5",
"@vercel/ncc": "0.27.0", "@vercel/ncc": "0.27.0",
"@vercel/nft": "0.12.2", "@vercel/nft": "0.12.2",
"amphtml-validator": "1.0.33", "amphtml-validator": "1.0.33",
...@@ -238,7 +237,8 @@ ...@@ -238,7 +237,8 @@
"postcss-value-parser": "4.1.0", "postcss-value-parser": "4.1.0",
"resolve-url-loader": "3.1.2", "resolve-url-loader": "3.1.2",
"sass-loader": "10.2.0", "sass-loader": "10.2.0",
"schema-utils": "2.7.1", "schema-utils2": "npm:schema-utils@2.7.1",
"schema-utils3": "npm:schema-utils@3.0.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",
...@@ -249,8 +249,14 @@ ...@@ -249,8 +249,14 @@
"text-table": "0.2.0", "text-table": "0.2.0",
"unistore": "3.4.1", "unistore": "3.4.1",
"web-vitals": "2.1.0", "web-vitals": "2.1.0",
"webpack": "4.44.1", "webpack4": "npm:webpack@4.44.1",
"webpack-sources": "1.4.3" "webpack5": "npm:webpack@5.53.0",
"webpack-sources1": "npm:webpack-sources@1.4.3",
"webpack-sources3": "npm:webpack-sources@3.2.0"
},
"resolutions": {
"browserslist": "4.16.6",
"caniuse-lite": "1.0.30001228"
}, },
"engines": { "engines": {
"node": ">=12.0.0" "node": ">=12.0.0"
......
...@@ -109,7 +109,7 @@ export type NextConfig = { [key: string]: any } & { ...@@ -109,7 +109,7 @@ export type NextConfig = { [key: string]: any } & {
webpack5?: false webpack5?: false
strictPostcssConfiguration?: boolean strictPostcssConfiguration?: boolean
} }
crossOrigin?: string crossOrigin?: false | 'anonymous' | 'use-credentials'
experimental?: { experimental?: {
swcMinify?: boolean swcMinify?: boolean
swcLoader?: boolean swcLoader?: boolean
......
...@@ -26,7 +26,7 @@ type ReactLoadableManifest = { [moduleId: string]: ManifestItem } ...@@ -26,7 +26,7 @@ type ReactLoadableManifest = { [moduleId: string]: ManifestItem }
export type LoadComponentsReturnType = { export type LoadComponentsReturnType = {
Component: React.ComponentType Component: React.ComponentType
pageConfig?: PageConfig pageConfig: PageConfig
buildManifest: BuildManifest buildManifest: BuildManifest
reactLoadableManifest: ReactLoadableManifest reactLoadableManifest: ReactLoadableManifest
Document: DocumentType Document: DocumentType
...@@ -47,6 +47,7 @@ export async function loadDefaultErrorComponents(distDir: string) { ...@@ -47,6 +47,7 @@ export async function loadDefaultErrorComponents(distDir: string) {
App, App,
Document, Document,
Component, Component,
pageConfig: {},
buildManifest: require(join(distDir, `fallback-${BUILD_MANIFEST}`)), buildManifest: require(join(distDir, `fallback-${BUILD_MANIFEST}`)),
reactLoadableManifest: {}, reactLoadableManifest: {},
ComponentMod, ComponentMod,
...@@ -59,13 +60,27 @@ export async function loadComponents( ...@@ -59,13 +60,27 @@ export async function loadComponents(
serverless: boolean serverless: boolean
): Promise<LoadComponentsReturnType> { ): Promise<LoadComponentsReturnType> {
if (serverless) { if (serverless) {
const Component = await requirePage(pathname, distDir, serverless) const ComponentMod = await requirePage(pathname, distDir, serverless)
let { getStaticProps, getStaticPaths, getServerSideProps } = Component if (typeof ComponentMod === 'string') {
return {
Component: ComponentMod as any,
pageConfig: {},
ComponentMod,
} as LoadComponentsReturnType
}
let {
default: Component,
getStaticProps,
getStaticPaths,
getServerSideProps,
} = ComponentMod
Component = await Component
getStaticProps = await getStaticProps getStaticProps = await getStaticProps
getStaticPaths = await getStaticPaths getStaticPaths = await getStaticPaths
getServerSideProps = await getServerSideProps getServerSideProps = await getServerSideProps
const pageConfig = (await Component.config) || {} const pageConfig = (await ComponentMod.config) || {}
return { return {
Component, Component,
...@@ -73,7 +88,7 @@ export async function loadComponents( ...@@ -73,7 +88,7 @@ export async function loadComponents(
getStaticProps, getStaticProps,
getStaticPaths, getStaticPaths,
getServerSideProps, getServerSideProps,
ComponentMod: Component, ComponentMod,
} as LoadComponentsReturnType } as LoadComponentsReturnType
} }
......
...@@ -1450,8 +1450,8 @@ export default class Server { ...@@ -1450,8 +1450,8 @@ export default class Server {
const is500Page = pathname === '/500' const is500Page = pathname === '/500'
const isLikeServerless = const isLikeServerless =
typeof components.Component === 'object' && typeof components.ComponentMod === 'object' &&
typeof (components.Component as any).renderReqToHTML === 'function' typeof (components.ComponentMod as any).renderReqToHTML === 'function'
const isSSG = !!components.getStaticProps const isSSG = !!components.getStaticProps
const hasServerProps = !!components.getServerSideProps const hasServerProps = !!components.getServerSideProps
const hasStaticPaths = !!components.getStaticPaths const hasStaticPaths = !!components.getStaticPaths
...@@ -1493,7 +1493,7 @@ export default class Server { ...@@ -1493,7 +1493,7 @@ export default class Server {
!isLikeServerless && !isLikeServerless &&
!query.amp && !query.amp &&
!this.minimalMode && !this.minimalMode &&
typeof components.Document.getInitialProps !== 'function' typeof components.Document?.getInitialProps !== 'function'
} }
const locale = query.__nextLocale as string const locale = query.__nextLocale as string
...@@ -1626,7 +1626,7 @@ export default class Server { ...@@ -1626,7 +1626,7 @@ export default class Server {
// handle serverless // handle serverless
if (isLikeServerless) { if (isLikeServerless) {
const renderResult = await ( const renderResult = await (
components.Component as any components.ComponentMod as any
).renderReqToHTML(req, res, 'passthrough', { ).renderReqToHTML(req, res, 'passthrough', {
locale, locale,
locales, locales,
......
...@@ -2,25 +2,8 @@ ...@@ -2,25 +2,8 @@
const notifier = require('node-notifier') const notifier = require('node-notifier')
// eslint-disable-next-line import/no-extraneous-dependencies // eslint-disable-next-line import/no-extraneous-dependencies
const { relative, basename, resolve, join } = require('path') const { relative, basename, resolve, join } = require('path')
const { Module } = require('module')
const fs = require('fs') const fs = require('fs')
// Note:
// "bundles" folder shadows main node_modules in workspace where all installs in
// this shadow node_modules are alias installs only.
// This is because Yarn alias installs have bugs with version deduping where
// transitive versions are not resolved correctly - for example, webpack5
// will end up resolving webpack-sources@1 instead of webpack-sources@2.
// If/when this issue is fixed upstream in Yarn, this "shadowing" workaround can
// then be removed to directly install the bundles/package.json packages into
// the main package.json as normal devDependencies aliases.
const m = new Module(resolve(__dirname, 'bundles', '_'))
m.filename = m.id
m.paths = Module._nodeModulePaths(m.id)
const bundleRequire = m.require
bundleRequire.resolve = (request, options) =>
Module._resolveFilename(request, m, false, options)
export async function next__polyfill_nomodule(task, opts) { export async function next__polyfill_nomodule(task, opts) {
await task await task
.source( .source(
...@@ -286,7 +269,13 @@ externals['file-loader'] = 'next/dist/compiled/file-loader' ...@@ -286,7 +269,13 @@ externals['file-loader'] = 'next/dist/compiled/file-loader'
export async function ncc_file_loader(task, opts) { export async function ncc_file_loader(task, opts) {
await task await task
.source(opts.src || relative(__dirname, require.resolve('file-loader'))) .source(opts.src || relative(__dirname, require.resolve('file-loader')))
.ncc({ packageName: 'file-loader', externals }) .ncc({
packageName: 'file-loader',
externals: {
...externals,
'schema-utils': externals['schema-utils2'],
},
})
.target('compiled/file-loader') .target('compiled/file-loader')
} }
// eslint-disable-next-line camelcase // eslint-disable-next-line camelcase
...@@ -600,32 +589,33 @@ export async function ncc_sass_loader(task, opts) { ...@@ -600,32 +589,33 @@ export async function ncc_sass_loader(task, opts) {
}, },
externals: { externals: {
...externals, ...externals,
'schema-utils': 'next/dist/compiled/schema-utils3', 'schema-utils': externals['schema-utils3'],
}, },
target: 'es5', target: 'es5',
}) })
.target('compiled/sass-loader') .target('compiled/sass-loader')
} }
// eslint-disable-next-line camelcase // eslint-disable-next-line camelcase
externals['schema-utils'] = 'next/dist/compiled/schema-utils' externals['schema-utils'] = 'MISSING_VERSION schema-utils version not specified'
export async function ncc_schema_utils(task, opts) { externals['schema-utils2'] = 'next/dist/compiled/schema-utils2'
export async function ncc_schema_utils2(task, opts) {
await task await task
.source(opts.src || relative(__dirname, require.resolve('schema-utils'))) .source(opts.src || relative(__dirname, require.resolve('schema-utils2')))
.ncc({ .ncc({
packageName: 'schema-utils', packageName: 'schema-utils',
bundleName: 'schema-utils2',
externals, externals,
}) })
.target('compiled/schema-utils') .target('compiled/schema-utils2')
} }
// eslint-disable-next-line camelcase // eslint-disable-next-line camelcase
externals['schema-utils3'] = 'next/dist/compiled/schema-utils3' externals['schema-utils3'] = 'next/dist/compiled/schema-utils3'
export async function ncc_schema_utils3(task, opts) { export async function ncc_schema_utils3(task, opts) {
await task await task
.source( .source(opts.src || relative(__dirname, require.resolve('schema-utils3')))
opts.src || relative(__dirname, bundleRequire.resolve('schema-utils3'))
)
.ncc({ .ncc({
packageName: 'schema-utils3', packageName: 'schema-utils',
bundleName: 'schema-utils3',
externals, externals,
}) })
.target('compiled/schema-utils3') .target('compiled/schema-utils3')
...@@ -712,19 +702,22 @@ export async function ncc_web_vitals(task, opts) { ...@@ -712,19 +702,22 @@ export async function ncc_web_vitals(task, opts) {
.target('compiled/web-vitals') .target('compiled/web-vitals')
} }
// eslint-disable-next-line camelcase // eslint-disable-next-line camelcase
externals['webpack-sources'] = 'next/dist/compiled/webpack-sources' externals['webpack-sources'] = 'error webpack-sources version not specified'
export async function ncc_webpack_sources(task, opts) { externals['webpack-sources1'] = 'next/dist/compiled/webpack-sources1'
export async function ncc_webpack_sources1(task, opts) {
await task await task
.source(opts.src || relative(__dirname, require.resolve('webpack-sources'))) .source(
.ncc({ packageName: 'webpack-sources', externals, target: 'es5' }) opts.src || relative(__dirname, require.resolve('webpack-sources1'))
.target('compiled/webpack-sources') )
.ncc({ packageName: 'webpack-sources1', externals, target: 'es5' })
.target('compiled/webpack-sources1')
} }
// eslint-disable-next-line camelcase // eslint-disable-next-line camelcase
externals['webpack-sources3'] = 'next/dist/compiled/webpack-sources3' externals['webpack-sources3'] = 'next/dist/compiled/webpack-sources3'
export async function ncc_webpack_sources3(task, opts) { export async function ncc_webpack_sources3(task, opts) {
await task await task
.source( .source(
opts.src || relative(__dirname, bundleRequire.resolve('webpack-sources3')) opts.src || relative(__dirname, require.resolve('webpack-sources3'))
) )
.ncc({ packageName: 'webpack-sources3', externals, target: 'es5' }) .ncc({ packageName: 'webpack-sources3', externals, target: 'es5' })
.target('compiled/webpack-sources3') .target('compiled/webpack-sources3')
...@@ -745,6 +738,7 @@ export async function ncc_mini_css_extract_plugin(task, opts) { ...@@ -745,6 +738,7 @@ export async function ncc_mini_css_extract_plugin(task, opts) {
...externals, ...externals,
'./index': './index.js', './index': './index.js',
'schema-utils': 'next/dist/compiled/schema-utils3', 'schema-utils': 'next/dist/compiled/schema-utils3',
'webpack-sources': externals['webpack-sources1'],
}, },
}) })
.target('compiled/mini-css-extract-plugin') .target('compiled/mini-css-extract-plugin')
...@@ -758,7 +752,7 @@ export async function ncc_mini_css_extract_plugin(task, opts) { ...@@ -758,7 +752,7 @@ export async function ncc_mini_css_extract_plugin(task, opts) {
externals: { externals: {
...externals, ...externals,
'./index': './index.js', './index': './index.js',
'schema-utils': 'next/dist/compiled/schema-utils3', 'schema-utils': externals['schema-utils3'],
}, },
}) })
.target('compiled/mini-css-extract-plugin') .target('compiled/mini-css-extract-plugin')
...@@ -768,6 +762,8 @@ export async function ncc_mini_css_extract_plugin(task, opts) { ...@@ -768,6 +762,8 @@ export async function ncc_mini_css_extract_plugin(task, opts) {
export async function ncc_webpack_bundle4(task, opts) { export async function ncc_webpack_bundle4(task, opts) {
const bundleExternals = { const bundleExternals = {
...externals, ...externals,
'schema-utils': externals['schema-utils2'],
'webpack-sources': externals['webpack-sources1'],
} }
for (const pkg of Object.keys(webpackBundlePackages)) { for (const pkg of Object.keys(webpackBundlePackages)) {
delete bundleExternals[pkg] delete bundleExternals[pkg]
...@@ -775,7 +771,7 @@ export async function ncc_webpack_bundle4(task, opts) { ...@@ -775,7 +771,7 @@ export async function ncc_webpack_bundle4(task, opts) {
await task await task
.source(opts.src || 'bundles/webpack/bundle4.js') .source(opts.src || 'bundles/webpack/bundle4.js')
.ncc({ .ncc({
packageName: 'webpack', packageName: 'webpack4',
bundleName: 'webpack', bundleName: 'webpack',
externals: bundleExternals, externals: bundleExternals,
minify: false, minify: false,
...@@ -788,6 +784,8 @@ export async function ncc_webpack_bundle4(task, opts) { ...@@ -788,6 +784,8 @@ export async function ncc_webpack_bundle4(task, opts) {
export async function ncc_webpack_bundle5(task, opts) { export async function ncc_webpack_bundle5(task, opts) {
const bundleExternals = { const bundleExternals = {
...externals, ...externals,
'schema-utils': externals['schema-utils3'],
'webpack-sources': externals['webpack-sources3'],
} }
for (const pkg of Object.keys(webpackBundlePackages)) { for (const pkg of Object.keys(webpackBundlePackages)) {
delete bundleExternals[pkg] delete bundleExternals[pkg]
...@@ -800,11 +798,7 @@ export async function ncc_webpack_bundle5(task, opts) { ...@@ -800,11 +798,7 @@ export async function ncc_webpack_bundle5(task, opts) {
customEmit(path) { customEmit(path) {
if (path.endsWith('.runtime.js')) return `'./${basename(path)}'` if (path.endsWith('.runtime.js')) return `'./${basename(path)}'`
}, },
externals: { externals: bundleExternals,
...bundleExternals,
'schema-utils': 'next/dist/compiled/schema-utils3',
'webpack-sources': 'next/dist/compiled/webpack-sources3',
},
minify: false, minify: false,
target: 'es5', target: 'es5',
}) })
...@@ -814,6 +808,8 @@ export async function ncc_webpack_bundle5(task, opts) { ...@@ -814,6 +808,8 @@ export async function ncc_webpack_bundle5(task, opts) {
const webpackBundlePackages = { const webpackBundlePackages = {
webpack: 'next/dist/compiled/webpack/webpack-lib', webpack: 'next/dist/compiled/webpack/webpack-lib',
'webpack/lib/NormalModule': 'next/dist/compiled/webpack/NormalModule', 'webpack/lib/NormalModule': 'next/dist/compiled/webpack/NormalModule',
'webpack/lib/node/NodeTargetPlugin':
'next/dist/compiled/webpack/NodeTargetPlugin',
} }
Object.assign(externals, webpackBundlePackages) Object.assign(externals, webpackBundlePackages)
...@@ -899,7 +895,7 @@ export async function ncc(task, opts) { ...@@ -899,7 +895,7 @@ export async function ncc(task, opts) {
'ncc_icss_utils', 'ncc_icss_utils',
'ncc_resolve_url_loader', 'ncc_resolve_url_loader',
'ncc_sass_loader', 'ncc_sass_loader',
'ncc_schema_utils', 'ncc_schema_utils2',
'ncc_schema_utils3', 'ncc_schema_utils3',
'ncc_semver', 'ncc_semver',
'ncc_send', 'ncc_send',
...@@ -914,7 +910,7 @@ export async function ncc(task, opts) { ...@@ -914,7 +910,7 @@ export async function ncc(task, opts) {
'ncc_webpack_bundle4', 'ncc_webpack_bundle4',
'ncc_webpack_bundle5', 'ncc_webpack_bundle5',
'ncc_webpack_bundle_packages', 'ncc_webpack_bundle_packages',
'ncc_webpack_sources', 'ncc_webpack_sources1',
'ncc_webpack_sources3', 'ncc_webpack_sources3',
'ncc_mini_css_extract_plugin', 'ncc_mini_css_extract_plugin',
], ],
......
...@@ -225,7 +225,7 @@ declare module 'next/dist/compiled/comment-json' { ...@@ -225,7 +225,7 @@ declare module 'next/dist/compiled/comment-json' {
} }
declare module 'pnp-webpack-plugin' { declare module 'pnp-webpack-plugin' {
import webpack from 'webpack' import webpack from 'webpack4'
class PnpWebpackPlugin extends webpack.Plugin {} class PnpWebpackPlugin extends webpack.Plugin {}
......
...@@ -27,20 +27,40 @@ declare module 'mini-css-extract-plugin' ...@@ -27,20 +27,40 @@ declare module 'mini-css-extract-plugin'
declare module 'next/dist/compiled/loader-utils' declare module 'next/dist/compiled/loader-utils'
declare module 'next/dist/compiled/webpack/webpack' { declare module 'next/dist/compiled/webpack/webpack' {
import webpackSources from 'webpack-sources' import webpackSources from 'webpack-sources1'
import webpack, { loader } from 'webpack' import webpack4, { loader } from 'webpack4'
export { NormalModule } from 'webpack'
export let isWebpack5: boolean export let isWebpack5: boolean
export function init(useWebpack5: boolean): void export function init(useWebpack5: boolean): void
export let BasicEvaluatedExpression: any export let BasicEvaluatedExpression: any
export let GraphHelpers: any export let GraphHelpers: any
export function onWebpackInit(cb: () => void): void export function onWebpackInit(cb: () => void): void
// TODO change this to webpack4 | webpack5
export let sources: typeof webpackSources export let sources: typeof webpackSources
export { webpack, loader } // TODO change this to webpack
export { webpack4 as webpack, loader }
} }
declare module 'webpack' { declare module 'webpack' {
import webpack4 from 'webpack4'
import webpack5 from 'webpack5'
export type Compiler = webpack4.Compiler | webpack5.Compiler
export type Compilation =
| webpack4.compilation.Compilation
| webpack5.Compilation
export type Module = webpack4.Module | webpack5.Module
export type Stats = webpack4.Stats | webpack5.Stats
export {
Template,
RuntimeModule,
RuntimeGlobals,
NormalModule,
} from 'webpack5'
}
declare module 'webpack4' {
import { RawSourceMap } from 'source-map' import { RawSourceMap } from 'source-map'
import { ConcatSource } from 'webpack-sources' import { ConcatSource } from 'webpack-sources1'
export = webpack export = webpack
......
...@@ -11,7 +11,7 @@ import { StackFrame } from 'stacktrace-parser' ...@@ -11,7 +11,7 @@ import { StackFrame } from 'stacktrace-parser'
import url from 'url' import url from 'url'
// @ts-ignore // @ts-ignore
// eslint-disable-next-line import/no-extraneous-dependencies // eslint-disable-next-line import/no-extraneous-dependencies
import webpack from 'webpack' import type webpack from 'webpack4'
import { getRawSourceMap } from './internal/helpers/getRawSourceMap' import { getRawSourceMap } from './internal/helpers/getRawSourceMap'
import { launchEditor } from './internal/helpers/launchEditor' import { launchEditor } from './internal/helpers/launchEditor'
......
// types only import
import { import {
Compiler as WebpackCompiler, Compiler as WebpackCompiler,
Template as WebpackTemplate, Template as WebpackTemplate,
// @ts-ignore exists in webpack 5
RuntimeModule as WebpackRuntimeModule, RuntimeModule as WebpackRuntimeModule,
// @ts-ignore exists in webpack 5
RuntimeGlobals as WebpackRuntimeGlobals, RuntimeGlobals as WebpackRuntimeGlobals,
// @ts-ignore exists in webpack 5 Compilation as WebpackCompilation,
compilation as WebpackCompilation,
} from 'webpack' } from 'webpack'
// Shared between webpack 4 and 5: // Shared between webpack 4 and 5:
function injectRefreshFunctions( function injectRefreshFunctions(
compilation: WebpackCompilation.Compilation, compilation: WebpackCompilation,
Template: typeof WebpackTemplate Template: typeof WebpackTemplate
) { ) {
const hookVars: any = (compilation.mainTemplate.hooks as any).localVars const hookVars: any = (compilation.mainTemplate.hooks as any).localVars
...@@ -97,7 +93,6 @@ function webpack5(this: ReactFreshWebpackPlugin, compiler: WebpackCompiler) { ...@@ -97,7 +93,6 @@ function webpack5(this: ReactFreshWebpackPlugin, compiler: WebpackCompiler) {
} }
generate() { generate() {
// @ts-ignore This exists in webpack 5
const { runtimeTemplate } = this.compilation const { runtimeTemplate } = this.compilation
return Template.asString([ return Template.asString([
`if (${RuntimeGlobals.interceptModuleExecution}) {`, `if (${RuntimeGlobals.interceptModuleExecution}) {`,
......
import { import type { LoaderDefinition } from 'webpack'
// @ts-ignore exists in webpack 5
loader,
} from 'webpack'
import RefreshModuleRuntime from './internal/ReactRefreshModule.runtime' import RefreshModuleRuntime from './internal/ReactRefreshModule.runtime'
let refreshModuleRuntime = RefreshModuleRuntime.toString() let refreshModuleRuntime = RefreshModuleRuntime.toString()
...@@ -10,7 +7,7 @@ refreshModuleRuntime = refreshModuleRuntime.slice( ...@@ -10,7 +7,7 @@ refreshModuleRuntime = refreshModuleRuntime.slice(
refreshModuleRuntime.lastIndexOf('}') refreshModuleRuntime.lastIndexOf('}')
) )
const ReactRefreshLoader: loader.Loader = function ReactRefreshLoader( const ReactRefreshLoader: LoaderDefinition = function ReactRefreshLoader(
source, source,
inputSourceMap inputSourceMap
) { ) {
......
...@@ -6,7 +6,10 @@ ...@@ -6,7 +6,10 @@
"target": "es2015", "target": "es2015",
"lib": ["dom"], "lib": ["dom"],
"downlevelIteration": true, "downlevelIteration": true,
"preserveWatchOutput": true "preserveWatchOutput": true,
"paths": {
"webpack": ["../../node_modules/webpack5"]
}
}, },
"include": ["**/*.ts"], "include": ["**/*.ts"],
"exclude": ["node_modules"] "exclude": ["node_modules"]
......
#!/bin/bash #!/bin/bash
yarn --cwd packages/next/bundles cp node_modules/webpack5/lib/hmr/HotModuleReplacement.runtime.js packages/next/bundles/webpack/packages/
cp packages/next/bundles/node_modules/webpack5/lib/hmr/HotModuleReplacement.runtime.js packages/next/bundles/webpack/packages/ cp node_modules/webpack5/lib/hmr/JavascriptHotModuleReplacement.runtime.js packages/next/bundles/webpack/packages/
cp packages/next/bundles/node_modules/webpack5/lib/hmr/JavascriptHotModuleReplacement.runtime.js packages/next/bundles/webpack/packages/
yarn --cwd packages/next ncc-compiled yarn --cwd packages/next ncc-compiled
# Make sure to exit with 1 if there are changes after running ncc-compiled # Make sure to exit with 1 if there are changes after running ncc-compiled
...@@ -10,6 +9,6 @@ yarn --cwd packages/next ncc-compiled ...@@ -10,6 +9,6 @@ yarn --cwd packages/next ncc-compiled
if [[ ! -z $(git status -s) ]];then if [[ ! -z $(git status -s) ]];then
echo "Detected changes" echo "Detected changes"
git status git diff -a --stat
exit 1 exit 1
fi fi
module.exports = { module.exports = {
// target: 'experimental-serverless-trace', // target: 'experimental-serverless-trace',
webpack: (config, options) => { webpack: (config) => {
config.experiments = { config.experiments = config.experiments || {}
topLevelAwait: true, config.experiments.topLevelAwait = true
}
return config return config
}, },
} }
import Head from 'next/head'
export const config = { export const config = {
amp: true, amp: true,
} }
...@@ -8,6 +10,14 @@ export default function Config() { ...@@ -8,6 +10,14 @@ export default function Config() {
const date = new Date() const date = new Date()
return ( return (
<div> <div>
<Head>
<script
async
key="amp-timeago"
custom-element="amp-timeago"
src="https://cdn.ampproject.org/v0/amp-timeago-0.1.js"
/>
</Head>
<amp-timeago <amp-timeago
id="amp-timeago" id="amp-timeago"
width="0" width="0"
......
...@@ -12,11 +12,10 @@ import { ...@@ -12,11 +12,10 @@ import {
nextBuild, nextBuild,
nextStart, nextStart,
File, File,
check,
} from 'next-test-utils' } from 'next-test-utils'
import { join } from 'path' import { join } from 'path'
import webpack from 'webpack'
const isWebpack5 = parseInt(webpack.version) === 5
let app let app
let appPort let appPort
const appDir = join(__dirname, '../') const appDir = join(__dirname, '../')
...@@ -83,7 +82,11 @@ function runTests(dev = false) { ...@@ -83,7 +82,11 @@ function runTests(dev = false) {
let browser let browser
try { try {
browser = await webdriver(appPort, '/config') browser = await webdriver(appPort, '/config')
expect(await browser.elementByCss('#amp-timeago').text()).not.toBe('fail') await check(
() => browser.elementByCss('#amp-timeago').text(),
'just now',
true
)
} finally { } finally {
if (browser) await browser.close() if (browser) await browser.close()
} }
...@@ -101,7 +104,11 @@ function runTests(dev = false) { ...@@ -101,7 +104,11 @@ function runTests(dev = false) {
}) })
} }
;(isWebpack5 ? describe : describe.skip)('Async modules', () => { describe('Async modules', () => {
if (process.env.NEXT_PRIVATE_TEST_WEBPACK4_MODE) {
it.skip("webpack 4 doesn't support top level await", () => {})
return
}
describe('dev mode', () => { describe('dev mode', () => {
beforeAll(async () => { beforeAll(async () => {
appPort = await findPort() appPort = await findPort()
......
...@@ -5,17 +5,10 @@ import { findPort, killApp, launchApp, nextBuild } from 'next-test-utils' ...@@ -5,17 +5,10 @@ import { findPort, killApp, launchApp, nextBuild } from 'next-test-utils'
import webdriver from 'next-webdriver' import webdriver from 'next-webdriver'
import { recursiveReadDir } from 'next/dist/lib/recursive-readdir' import { recursiveReadDir } from 'next/dist/lib/recursive-readdir'
import { join } from 'path' import { join } from 'path'
import { version } from 'webpack'
const isWebpack5 = parseInt(version) === 5
const appDir = join(__dirname, '../') const appDir = join(__dirname, '../')
// TODO: Make legacy Sass support work with webpack 5 describe('Legacy Sass Support Should Disable New CSS', () => {
const describeFn = isWebpack5 ? describe.skip : describe
// TODO: Make legacy Sass support work with webpack 5
describeFn('Legacy Sass Support Should Disable New CSS', () => {
beforeAll(async () => { beforeAll(async () => {
await remove(join(appDir, '.next')) await remove(join(appDir, '.next'))
await nextBuild(appDir) await nextBuild(appDir)
...@@ -31,7 +24,7 @@ describeFn('Legacy Sass Support Should Disable New CSS', () => { ...@@ -31,7 +24,7 @@ describeFn('Legacy Sass Support Should Disable New CSS', () => {
}) })
}) })
describeFn('Legacy Sass Support should work in development', () => { describe('Legacy Sass Support should work in development', () => {
beforeAll(async () => { beforeAll(async () => {
await remove(join(appDir, '.next')) await remove(join(appDir, '.next'))
}) })
......
...@@ -3,30 +3,25 @@ ...@@ -3,30 +3,25 @@
import webdriver from 'next-webdriver' import webdriver from 'next-webdriver'
import { join } from 'path' import { join } from 'path'
import { import {
nextServer, nextStart,
nextBuild, nextBuild,
startApp, findPort,
stopApp, killApp,
runNextCommand, runNextCommand,
} from 'next-test-utils' } from 'next-test-utils'
const appDir = join(__dirname, '../') const appDir = join(__dirname, '../')
let app
let appPort let appPort
let server
describe('Production Config Usage', () => { describe('Production Config Usage', () => {
beforeAll(async () => { beforeAll(async () => {
await nextBuild(appDir) await nextBuild(appDir)
const app = nextServer({ appPort = await findPort()
dir: join(__dirname, '../'), app = await nextStart(appDir, appPort)
dev: false,
quiet: true,
}) })
server = await startApp(app) afterAll(() => killApp(app))
appPort = server.address().port
})
afterAll(() => stopApp(server))
describe('with next-css', () => { describe('with next-css', () => {
it('should load styles', async () => { it('should load styles', async () => {
......
...@@ -17,6 +17,7 @@ export class NextInstance { ...@@ -17,6 +17,7 @@ export class NextInstance {
protected dependencies?: { [name: string]: string } protected dependencies?: { [name: string]: string }
protected events: { [eventName: string]: Set<any> } protected events: { [eventName: string]: Set<any> }
protected testDir: string protected testDir: string
protected isStopping: boolean
protected isDestroyed: boolean protected isDestroyed: boolean
protected childProcess: ChildProcess protected childProcess: ChildProcess
protected _url: string protected _url: string
...@@ -40,6 +41,7 @@ export class NextInstance { ...@@ -40,6 +41,7 @@ export class NextInstance {
this.nextConfig = nextConfig this.nextConfig = nextConfig
this.events = {} this.events = {}
this.isDestroyed = false this.isDestroyed = false
this.isStopping = false
} }
protected async createTestDir() { protected async createTestDir() {
...@@ -120,6 +122,7 @@ export class NextInstance { ...@@ -120,6 +122,7 @@ export class NextInstance {
public async setup(): Promise<void> {} public async setup(): Promise<void> {}
public async start(): Promise<void> {} public async start(): Promise<void> {}
public async stop(): Promise<void> { public async stop(): Promise<void> {
this.isStopping = true
if (this.childProcess) { if (this.childProcess) {
let exitResolve let exitResolve
const exitPromise = new Promise((resolve) => { const exitPromise = new Promise((resolve) => {
......
...@@ -49,6 +49,7 @@ export class NextDevInstance extends NextInstance { ...@@ -49,6 +49,7 @@ export class NextDevInstance extends NextInstance {
}) })
this.childProcess.on('close', (code) => { this.childProcess.on('close', (code) => {
if (this.isStopping) return
if (code) { if (code) {
throw new Error(`next dev exited unexpectedly with code ${code}`) throw new Error(`next dev exited unexpectedly with code ${code}`)
} }
......
...@@ -81,6 +81,13 @@ export class NextStartInstance extends NextInstance { ...@@ -81,6 +81,13 @@ export class NextStartInstance extends NextInstance {
) )
handleStdio() handleStdio()
this.childProcess.on('close', (code) => {
if (this.isStopping) return
if (code) {
throw new Error(`next start exited unexpectedly with code ${code}`)
}
})
await new Promise<void>((resolve) => { await new Promise<void>((resolve) => {
const readyCb = (msg) => { const readyCb = (msg) => {
if (msg.includes('started server on') && msg.includes('url:')) { if (msg.includes('started server on') && msg.includes('url:')) {
......
...@@ -10,9 +10,6 @@ import { ...@@ -10,9 +10,6 @@ import {
import { writeFile } from 'fs-extra' import { writeFile } from 'fs-extra'
import getPort from 'get-port' import getPort from 'get-port'
import http from 'http' import http from 'http'
// `next` here is the symlink in `test/node_modules/next` which points to the root directory.
// This is done so that requiring from `next` works.
// The reason we don't import the relative path `../../dist/<etc>` is that it would lead to inconsistent module singletons
import server from 'next/dist/server/next' import server from 'next/dist/server/next'
import _pkg from 'next/package.json' import _pkg from 'next/package.json'
import fetch from 'node-fetch' import fetch from 'node-fetch'
......
This diff is collapsed.
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