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:
- uses: actions/cache@v2
id: cache-build
with:
path: ./*
path: |
./*
!./.git
key: ${{ github.sha }}
lint:
......@@ -63,7 +65,9 @@ jobs:
- uses: actions/cache@v2
id: restore-build
with:
path: ./*
path: |
./*
!./.git
key: ${{ github.sha }}
- run: ./scripts/check-manifests.js
- run: yarn lint
......@@ -75,29 +79,44 @@ jobs:
env:
NEXT_TELEMETRY_DISABLED: 1
steps:
- uses: actions/checkout@v2
if: ${{needs.build.outputs.docsChange != 'docs only change'}}
# https://github.com/actions/virtual-environments/issues/1187
- name: tune linux network
if: ${{needs.build.outputs.docsChange != 'docs only change'}}
run: sudo ethtool -K eth0 tx off rx off
- uses: actions/cache@v2
if: ${{needs.build.outputs.docsChange != 'docs only change'}}
id: restore-build
with:
path: ./*
path: |
./*
!./.git
key: ${{ github.sha }}
- uses: actions/download-artifact@v2
if: ${{needs.build.outputs.docsChange != 'docs only change'}}
with:
name: next-swc-binaries
path: packages/next/build/swc/dist
# Only check linux build for now, mac builds can sometimes be different even with the same code
- run: |
mv ./packages/next/build/swc/dist/next-swc.linux-x64-gnu.node \
./packages/next/native/next-swc.linux-x64-gnu.node
if: ${{needs.build.outputs.docsChange != 'docs only change'}}
- run: ./scripts/check-pre-compiled.sh
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:
name: Test Unit
runs-on: ubuntu-latest
......@@ -110,7 +129,9 @@ jobs:
if: ${{needs.build.outputs.docsChange != 'docs only change'}}
id: restore-build
with:
path: ./*
path: |
./*
!./.git
key: ${{ github.sha }}
- run: node run-tests.js --type unit
......@@ -134,7 +155,9 @@ jobs:
if: ${{needs.build.outputs.docsChange != 'docs only change'}}
id: restore-build
with:
path: ./*
path: |
./*
!./.git
key: ${{ github.sha }}
- run: npm i -g playwright-chromium@1.14.1 && npx playwright install-deps
......@@ -170,7 +193,9 @@ jobs:
if: ${{needs.build.outputs.docsChange != 'docs only change'}}
id: restore-build
with:
path: ./*
path: |
./*
!./.git
key: ${{ github.sha }}
- run: npm i -g playwright-chromium@1.14.1 && npx playwright install-deps
......@@ -210,7 +235,9 @@ jobs:
if: ${{needs.build.outputs.docsChange != 'docs only change'}}
id: restore-build
with:
path: ./*
path: |
./*
!./.git
key: ${{ github.sha }}
- run: npm i -g playwright-chromium@1.14.1 && npx playwright install-deps
......@@ -236,7 +263,9 @@ jobs:
if: ${{needs.build.outputs.docsChange != 'docs only change'}}
id: restore-build
with:
path: ./*
path: |
./*
!./.git
key: ${{ github.sha }}
# TODO: remove after we fix watchpack watching too much
......@@ -260,7 +289,9 @@ jobs:
if: ${{needs.build.outputs.docsChange != 'docs only change'}}
id: restore-build
with:
path: ./*
path: |
./*
!./.git
key: ${{ github.sha }}
- run: bash ./scripts/test-pnp.sh
......@@ -272,6 +303,8 @@ jobs:
needs:
[
lint,
check-examples,
test-native,
checkPrecompiled,
testIntegration,
testUnit,
......@@ -300,7 +333,9 @@ jobs:
if: ${{needs.build.outputs.docsChange != 'docs only change'}}
id: restore-build
with:
path: ./*
path: |
./*
!./.git
key: ${{ github.sha }}
- run: npm i -g playwright-chromium@1.14.1 && npx playwright install-deps
......@@ -321,7 +356,9 @@ jobs:
if: ${{needs.build.outputs.docsChange != 'docs only change'}}
id: restore-build
with:
path: ./*
path: |
./*
!./.git
key: ${{ github.sha }}
- run: npx playwright install-deps && npx playwright install firefox
if: ${{needs.build.outputs.docsChange != 'docs only change'}}
......@@ -348,7 +385,9 @@ jobs:
if: ${{needs.build.outputs.docsChange != 'docs only change'}}
id: restore-build
with:
path: ./*
path: |
./*
!./.git
key: ${{ github.sha }}
# TODO: use macos runner so that we can use playwright to test against
......@@ -380,7 +419,9 @@ jobs:
if: ${{needs.build.outputs.docsChange != 'docs only change'}}
id: restore-build
with:
path: ./*
path: |
./*
!./.git
key: ${{ github.sha }}
- run: '[[ -z "$BROWSERSTACK_ACCESS_KEY" ]] && echo "Skipping for PR" || npm i -g browserstack-local@1.4.0'
......@@ -404,7 +445,9 @@ jobs:
- uses: actions/cache@v2
id: restore-build
with:
path: ./*
path: |
./*
!./.git
key: ${{ github.sha }}
- uses: actions/download-artifact@v2
with:
......@@ -422,7 +465,9 @@ jobs:
- uses: actions/cache@v2
id: restore-build
with:
path: ./*
path: |
./*
!./.git
key: ${{ github.sha }}
- run: ./scripts/release-stats.sh
- uses: ./.github/actions/next-stats-action
......
{
"name": "nextjs-project",
"version": "0.0.0",
"private": true,
"workspaces": [
"packages/*"
......@@ -61,6 +62,24 @@
"@typescript-eslint/eslint-plugin": "4.29.1",
"@typescript-eslint/parser": "4.29.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-sass": "1.0.2-canary.2",
"@zeit/next-typescript": "1.1.2-canary.0",
......@@ -68,7 +87,7 @@
"alex": "9.1.0",
"amphtml-validator": "1.0.33",
"async-sema": "3.0.1",
"browserslist": "^4.14.7",
"browserslist": "4.16.6",
"cheerio": "0.22.0",
"clone": "2.1.2",
"cookie": "0.4.1",
......
......@@ -10,6 +10,7 @@ import { ClientPagesLoaderOptions } from './webpack/loaders/next-client-pages-lo
import { ServerlessLoaderQuery } from './webpack/loaders/next-serverless-loader'
import { LoadedEnvFiles } from '@next/env'
import { NextConfigComplete } from '../server/config-shared'
import type webpack5 from 'webpack5'
type PagesMapping = {
[page: string]: string
......@@ -62,21 +63,9 @@ export function createPagesMapping(
return pages
}
export type WebpackEntrypoints = {
[bundle: string]:
| string
| string[]
| {
import: string | string[]
dependOn?: string | string[]
publicPath?: string
runtime?: string
}
}
type Entrypoints = {
client: WebpackEntrypoints
server: WebpackEntrypoints
client: webpack5.EntryObject
server: webpack5.EntryObject
}
export function createEntrypoints(
......@@ -87,8 +76,8 @@ export function createEntrypoints(
config: NextConfigComplete,
loadedEnvFiles: LoadedEnvFiles
): Entrypoints {
const client: WebpackEntrypoints = {}
const server: WebpackEntrypoints = {}
const client: webpack5.EntryObject = {}
const server: webpack5.EntryObject = {}
const hasRuntimeConfig =
Object.keys(config.publicRuntimeConfig).length > 0 ||
......
......@@ -840,22 +840,25 @@ export async function isPageStatic(
try {
require('../shared/lib/runtime-config').setConfig(runtimeEnvConfig)
setHttpAgentOptions(httpAgentOptions)
const components = await loadComponents(distDir, page, serverless)
const mod = components.ComponentMod
const Comp = mod.default || mod
const mod = await loadComponents(distDir, page, serverless)
const Comp = mod.Component
if (!Comp || !isValidElementType(Comp) || typeof Comp === 'string') {
throw new Error('INVALID_DEFAULT_EXPORT')
}
const hasGetInitialProps = !!(Comp as any).getInitialProps
const hasStaticProps = !!(await mod.getStaticProps)
const hasStaticPaths = !!(await mod.getStaticPaths)
const hasServerProps = !!(await mod.getServerSideProps)
const hasLegacyServerProps = !!(await mod.unstable_getServerProps)
const hasLegacyStaticProps = !!(await mod.unstable_getStaticProps)
const hasLegacyStaticPaths = !!(await mod.unstable_getStaticPaths)
const hasLegacyStaticParams = !!(await mod.unstable_getStaticParams)
const hasStaticProps = !!mod.getStaticProps
const hasStaticPaths = !!mod.getStaticPaths
const hasServerProps = !!mod.getServerSideProps
const hasLegacyServerProps = !!(await mod.ComponentMod
.unstable_getServerProps)
const hasLegacyStaticProps = !!(await mod.ComponentMod
.unstable_getStaticProps)
const hasLegacyStaticPaths = !!(await mod.ComponentMod
.unstable_getStaticPaths)
const hasLegacyStaticParams = !!(await mod.ComponentMod
.unstable_getStaticParams)
if (hasLegacyStaticParams) {
throw new Error(
......@@ -921,14 +924,14 @@ export async function isPageStatic(
encodedPaths: encodedPrerenderRoutes,
} = await buildStaticPaths(
page,
mod.getStaticPaths,
mod.getStaticPaths!,
locales,
defaultLocale
))
}
const isNextImageImported = (global as any).__NEXT_IMAGE_IMPORTED
const config: PageConfig = mod.config || {}
const config: PageConfig = mod.pageConfig
return {
isStatic: !hasStaticProps && !hasGetInitialProps && !hasServerProps,
isHybridAmp: config.amp === 'hybrid',
......
......@@ -5,6 +5,7 @@ import { readFileSync } from 'fs'
import { codeFrameColumns } from 'next/dist/compiled/babel/code-frame'
import semver from 'next/dist/compiled/semver'
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 {
DOT_NEXT_ALIAS,
......@@ -28,7 +29,7 @@ import {
} from '../shared/lib/constants'
import { execOnce } from '../shared/lib/utils'
import { NextConfigComplete } from '../server/config-shared'
import { finalizeEntrypoint, WebpackEntrypoints } from './entries'
import { finalizeEntrypoint } from './entries'
import * as Log from './output/log'
import { build as buildConfiguration } from './webpack/config'
import { __overrideCssConfiguration } from './webpack/config/blocks/css/overrideCssConfiguration'
......@@ -224,7 +225,7 @@ export default async function getBaseWebpackConfig(
pagesDir: string
target?: string
reactProductionProfiling?: boolean
entrypoints: WebpackEntrypoints
entrypoints: webpack5.EntryObject
rewrites: CustomRoutes['rewrites']
isDevFallback?: boolean
runWebpackSpan: Span
......@@ -1379,16 +1380,21 @@ export default async function getBaseWebpackConfig(
// futureEmitAssets is on by default in webpack 5
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,
}
webpackConfig.module!.parser = {
webpack5Config.module!.parser = {
javascript: {
url: 'relative',
},
}
webpackConfig.module!.generator = {
webpack5Config.module!.generator = {
asset: {
filename: 'static/media/[name].[hash:8][ext]',
},
......@@ -1396,24 +1402,19 @@ export default async function getBaseWebpackConfig(
if (isServer && dev) {
// Enable building of client compilation before server compilation in development
// @ts-ignore dependencies exists
webpackConfig.dependencies = ['client']
webpack5Config.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
// This restores the webpack defaults
// @ts-ignore webpack 5
webpackConfig.snapshot = {}
webpack5Config.snapshot = {}
if (process.versions.pnp === '3') {
const match =
/^(.+?)[\\/]cache[\\/]jest-worker-npm-[^\\/]+\.zip[\\/]node_modules[\\/]/.exec(
require.resolve('jest-worker')
)
if (match) {
// @ts-ignore webpack 5
webpackConfig.snapshot.managedPaths = [
webpack5Config.snapshot.managedPaths = [
path.resolve(match[1], 'unplugged'),
]
}
......@@ -1422,8 +1423,7 @@ export default async function getBaseWebpackConfig(
require.resolve('jest-worker')
)
if (match) {
// @ts-ignore webpack 5
webpackConfig.snapshot.managedPaths = [match[1]]
webpack5Config.snapshot.managedPaths = [match[1]]
}
}
if (process.versions.pnp === '1') {
......@@ -1432,8 +1432,7 @@ export default async function getBaseWebpackConfig(
require.resolve('jest-worker')
)
if (match) {
// @ts-ignore webpack 5
webpackConfig.snapshot.immutablePaths = [match[1]]
webpack5Config.snapshot.immutablePaths = [match[1]]
}
} else if (process.versions.pnp === '3') {
const match =
......@@ -1441,17 +1440,16 @@ export default async function getBaseWebpackConfig(
require.resolve('jest-worker')
)
if (match) {
// @ts-ignore webpack 5
webpackConfig.snapshot.immutablePaths = [match[1]]
webpack5Config.snapshot.immutablePaths = [match[1]]
}
}
if (dev) {
if (!webpackConfig.optimization) {
webpackConfig.optimization = {}
if (!webpack5Config.optimization) {
webpack5Config.optimization = {}
}
webpackConfig.optimization.providedExports = false
webpackConfig.optimization.usedExports = false
webpack5Config.optimization.providedExports = false
webpack5Config.optimization.usedExports = false
}
const configVars = JSON.stringify({
......@@ -1496,7 +1494,7 @@ export default async function getBaseWebpackConfig(
}
}
webpackConfig.cache = cache
webpack5Config.cache = cache
if (process.env.NEXT_WEBPACK_LOGGING) {
const logInfra =
......@@ -1508,8 +1506,7 @@ export default async function getBaseWebpackConfig(
const logDefault = !logInfra && !logProfileClient && !logProfileServer
if (logDefault || logInfra) {
// @ts-ignore TODO: remove ignore when webpack 5 is stable
webpackConfig.infrastructureLogging = {
webpack5Config.infrastructureLogging = {
level: 'verbose',
debug: /FileSystemInfo/,
}
......@@ -1520,12 +1517,11 @@ export default async function getBaseWebpackConfig(
(logProfileClient && !isServer) ||
(logProfileServer && isServer)
) {
webpackConfig.plugins!.push((compiler: webpack.Compiler) => {
webpack5Config.plugins!.push((compiler: webpack5.Compiler) => {
compiler.hooks.done.tap('next-webpack-logging', (stats) => {
console.log(
stats.toString({
colors: true,
// @ts-ignore TODO: remove ignore when webpack 5 is stable
logging: logDefault ? 'log' : 'verbose',
})
)
......@@ -1534,13 +1530,14 @@ export default async function getBaseWebpackConfig(
}
if ((logProfileClient && !isServer) || (logProfileServer && isServer)) {
webpackConfig.plugins!.push(
new webpack.ProgressPlugin({
// @ts-ignore TODO: remove ignore when webpack 5 is stable
const ProgressPlugin =
webpack.ProgressPlugin as unknown as typeof webpack5.ProgressPlugin
webpack5Config.plugins!.push(
new ProgressPlugin({
profile: true,
})
)
webpackConfig.profile = true
webpack5Config.profile = true
}
}
}
......@@ -1897,7 +1894,7 @@ export default async function getBaseWebpackConfig(
const originalEntry: any = webpackConfig.entry
if (typeof originalEntry !== 'undefined') {
const updatedEntry = async () => {
const entry: WebpackEntrypoints =
const entry: webpack5.EntryObject =
typeof originalEntry === 'function'
? await originalEntry()
: originalEntry
......
......@@ -4,7 +4,10 @@ import { Transform, TransformCallback } from 'stream'
// @ts-ignore no types package
import bfj from 'next/dist/compiled/bfj'
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
......@@ -121,21 +124,29 @@ export default class BuildStatsPlugin {
const writeStatsSpan = compilationSpan!.traceChild('NextJsBuildStats')
await writeStatsSpan.traceAsyncFn(() => {
return new Promise((resolve, reject) => {
const baseOptions = {
all: false,
cached: true,
reasons: true,
entrypoints: true,
chunks: true,
errors: false,
warnings: false,
maxModules: Infinity,
chunkModules: true,
modules: true,
}
const statsJson = reduceSize(
stats.toJson({
all: false,
cached: true,
reasons: true,
entrypoints: true,
chunks: true,
errors: false,
warnings: false,
maxModules: Infinity,
chunkModules: true,
modules: true,
// @ts-ignore this option exists
ids: true,
})
isWebpack5
? (stats as webpack5.Stats).toJson({
...baseOptions,
modulesSpace: Infinity,
ids: true,
})
: (stats as webpack4.Stats).toJson({
...baseOptions,
maxModules: Infinity,
})
)
const fileStream = fs.createWriteStream(
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 type webpack from 'webpack'
const pluginName = 'ProfilingPlugin'
export const spans = new WeakMap<
webpack.compilation.Compilation | webpack.Compiler,
Span
>()
export const spans = new WeakMap<webpack.Compilation | webpack.Compiler, Span>()
const moduleSpansByCompilation = new WeakMap<
webpack.compilation.Compilation,
webpack.Compilation,
WeakMap<webpack.Module, Span>
>()
export const webpackInvalidSpans = new WeakMap<any, Span>()
......@@ -15,7 +13,7 @@ export const webpackInvalidSpans = new WeakMap<any, Span>()
function getNormalModuleLoaderHook(compilation: any) {
if (isWebpack5) {
// @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
......
......@@ -33,6 +33,78 @@ const hookPropertyMap = new Map(
'webpack/lib/node/NodeTargetPlugin.js',
'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',
'next/dist/compiled/webpack/ModuleFilenameHelpers',
......@@ -63,3 +135,6 @@ mod._resolveFilename = function (
if (hookResolved) request = hookResolved
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 @@
module.exports = function () {
return {
BasicEvaluatedExpression: require('webpack/lib/BasicEvaluatedExpression'),
NodeEnvironmentPlugin: require('webpack/lib/node/NodeEnvironmentPlugin'),
NodeTargetPlugin: require('webpack/lib/node/NodeTargetPlugin'),
ModuleFilenameHelpers: require('webpack/lib/ModuleFilenameHelpers'),
GraphHelpers: require('webpack/lib/GraphHelpers'),
Module: require('webpack/lib/Module'),
NormalModule: require('webpack/lib/NormalModule'),
Dependency: require('webpack/lib/Dependency'),
LibraryTemplatePlugin: require('webpack/lib/LibraryTemplatePlugin'),
SingleEntryPlugin: require('webpack/lib/SingleEntryPlugin'),
node: require('webpack').node,
util: require('webpack').util,
optimize: require('webpack').optimize,
BasicEvaluatedExpression: require('webpack4/lib/BasicEvaluatedExpression'),
NodeEnvironmentPlugin: require('webpack4/lib/node/NodeEnvironmentPlugin'),
NodeTargetPlugin: require('webpack4/lib/node/NodeTargetPlugin'),
NodeTemplatePlugin: require('webpack4/lib/node/NodeTemplatePlugin'),
ModuleFilenameHelpers: require('webpack4/lib/ModuleFilenameHelpers'),
GraphHelpers: require('webpack4/lib/GraphHelpers'),
Module: require('webpack4/lib/Module'),
NormalModule: require('webpack4/lib/NormalModule'),
Dependency: require('webpack4/lib/Dependency'),
LibraryTemplatePlugin: require('webpack4/lib/LibraryTemplatePlugin'),
SingleEntryPlugin: require('webpack4/lib/SingleEntryPlugin'),
FetchCompileWasmTemplatePlugin: require('webpack4/lib/web/FetchCompileWasmTemplatePlugin'),
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'),
webpack: require('webpack'),
webpack: require('webpack4'),
package: {
version: require('webpack/package.json').version,
version: require('webpack4/package.json').version,
},
}
}
......@@ -5,9 +5,20 @@ module.exports = function () {
BasicEvaluatedExpression: require('webpack5/lib/javascript/BasicEvaluatedExpression'),
ModuleFilenameHelpers: require('webpack5/lib/ModuleFilenameHelpers'),
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'),
NormalModule: require('webpack/lib/NormalModule'),
NormalModule: require('webpack5/lib/NormalModule'),
sources: require('webpack5').sources,
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)})();
\ No newline at end of file
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
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 =
/******/ (function() { // webpackBootstrap
/******/ var __webpack_modules__ = ({
/***/ 441:
/***/ 950:
/***/ (function(module) {
module.exports = function() {
......@@ -50,6 +50,6 @@ module.exports = function() {
/******/ // module exports must be returned from runtime so entry inlining is disabled
/******/ // startup
/******/ // 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 =
/******/ (function() { // webpackBootstrap
/******/ var __webpack_modules__ = ({
/***/ 929:
/***/ 560:
/***/ (function(module) {
/* globals __webpack_amd_options__ */
......@@ -49,6 +49,6 @@ module.exports = __webpack_amd_options__;
/******/ // module exports must be returned from runtime so entry inlining is disabled
/******/ // startup
/******/ // 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 =
/******/ (function() { // webpackBootstrap
/******/ var __webpack_modules__ = ({
/***/ 149:
/***/ 868:
/***/ (function(module) {
var g;
......@@ -67,6 +67,6 @@ module.exports = g;
/******/ // module exports must be returned from runtime so entry inlining is disabled
/******/ // startup
/******/ // 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 =
/******/ (function() { // webpackBootstrap
/******/ var __webpack_modules__ = ({
/***/ 931:
/***/ 460:
/***/ (function(module) {
module.exports = function(originalModule) {
......@@ -71,6 +71,6 @@ module.exports = function(originalModule) {
/******/ // module exports must be returned from runtime so entry inlining is disabled
/******/ // startup
/******/ // 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 =
/******/ "use strict";
/******/ var __webpack_modules__ = ({
/***/ 887:
/***/ 668:
/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
var __resourceQuery = "";
......@@ -94,6 +94,6 @@ module.exports = require("http");;
/******/ // module exports must be returned from runtime so entry inlining is disabled
/******/ // startup
/******/ // 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 =
/******/ "use strict";
/******/ var __webpack_modules__ = ({
/***/ 949:
/***/ 590:
/***/ (function(__unused_webpack_module, exports) {
var __resourceQuery = "";
......@@ -123,6 +123,6 @@ exports.keepAlive = function (options) {
/******/ // module exports must be returned from runtime so entry inlining is disabled
/******/ // startup
/******/ // 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 =
/******/ (function() { // webpackBootstrap
/******/ var __webpack_modules__ = ({
/***/ 880:
/***/ 767:
/***/ (function(module) {
module.exports = function(module) {
......@@ -69,6 +69,6 @@ module.exports = function(module) {
/******/ // module exports must be returned from runtime so entry inlining is disabled
/******/ // startup
/******/ // 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 =
/******/ (function() { // webpackBootstrap
/******/ var __webpack_modules__ = ({
/***/ 957:
/***/ 20:
/***/ (function(module) {
// Provide a "System" global.
......@@ -54,6 +54,6 @@ module.exports = {
/******/ // module exports must be returned from runtime so entry inlining is disabled
/******/ // startup
/******/ // 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({
},
})
const {
Component: mod,
Component,
ComponentMod,
getServerSideProps,
getStaticProps,
pageConfig,
} = await loadComponents(distDir, page, serverless)
const ampState = {
......@@ -274,25 +276,22 @@ export default async function exportPage({
}
// if it was auto-exported the HTML is loaded here
if (typeof mod === 'string') {
renderResult = RenderResult.fromStatic(mod)
if (typeof Component === 'string') {
renderResult = RenderResult.fromStatic(Component)
queryWithAutoExportWarn()
} else {
// for non-dynamic SSG pages we should have already
// prerendered the file
if (renderedDuringBuild((mod as ComponentModule).getStaticProps))
if (renderedDuringBuild(getStaticProps))
return { ...results, duration: Date.now() - start }
if (
(mod as ComponentModule).getStaticProps &&
!htmlFilepath.endsWith('.html')
) {
if (getStaticProps && !htmlFilepath.endsWith('.html')) {
// make sure it ends with .html if the name contains a dot
htmlFilename += '.html'
htmlFilepath += '.html'
}
renderMethod = (mod as ComponentModule).renderReqToHTML
renderMethod = (ComponentMod as ComponentModule).renderReqToHTML
const result = await renderMethod(
req,
res,
......
......@@ -183,8 +183,7 @@
"@types/send": "0.14.4",
"@types/styled-jsx": "2.2.8",
"@types/text-table": "0.2.1",
"@types/webpack": "5.28.0",
"@types/webpack-sources": "0.1.5",
"@types/webpack-sources1": "npm:@types/webpack-sources@0.1.5",
"@vercel/ncc": "0.27.0",
"@vercel/nft": "0.12.2",
"amphtml-validator": "1.0.33",
......@@ -238,7 +237,8 @@
"postcss-value-parser": "4.1.0",
"resolve-url-loader": "3.1.2",
"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",
"send": "0.17.1",
"source-map": "0.6.1",
......@@ -249,8 +249,14 @@
"text-table": "0.2.0",
"unistore": "3.4.1",
"web-vitals": "2.1.0",
"webpack": "4.44.1",
"webpack-sources": "1.4.3"
"webpack4": "npm:webpack@4.44.1",
"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": {
"node": ">=12.0.0"
......
......@@ -109,7 +109,7 @@ export type NextConfig = { [key: string]: any } & {
webpack5?: false
strictPostcssConfiguration?: boolean
}
crossOrigin?: string
crossOrigin?: false | 'anonymous' | 'use-credentials'
experimental?: {
swcMinify?: boolean
swcLoader?: boolean
......
......@@ -26,7 +26,7 @@ type ReactLoadableManifest = { [moduleId: string]: ManifestItem }
export type LoadComponentsReturnType = {
Component: React.ComponentType
pageConfig?: PageConfig
pageConfig: PageConfig
buildManifest: BuildManifest
reactLoadableManifest: ReactLoadableManifest
Document: DocumentType
......@@ -47,6 +47,7 @@ export async function loadDefaultErrorComponents(distDir: string) {
App,
Document,
Component,
pageConfig: {},
buildManifest: require(join(distDir, `fallback-${BUILD_MANIFEST}`)),
reactLoadableManifest: {},
ComponentMod,
......@@ -59,13 +60,27 @@ export async function loadComponents(
serverless: boolean
): Promise<LoadComponentsReturnType> {
if (serverless) {
const Component = await requirePage(pathname, distDir, serverless)
let { getStaticProps, getStaticPaths, getServerSideProps } = Component
const ComponentMod = await requirePage(pathname, distDir, serverless)
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
getStaticPaths = await getStaticPaths
getServerSideProps = await getServerSideProps
const pageConfig = (await Component.config) || {}
const pageConfig = (await ComponentMod.config) || {}
return {
Component,
......@@ -73,7 +88,7 @@ export async function loadComponents(
getStaticProps,
getStaticPaths,
getServerSideProps,
ComponentMod: Component,
ComponentMod,
} as LoadComponentsReturnType
}
......
......@@ -1450,8 +1450,8 @@ export default class Server {
const is500Page = pathname === '/500'
const isLikeServerless =
typeof components.Component === 'object' &&
typeof (components.Component as any).renderReqToHTML === 'function'
typeof components.ComponentMod === 'object' &&
typeof (components.ComponentMod as any).renderReqToHTML === 'function'
const isSSG = !!components.getStaticProps
const hasServerProps = !!components.getServerSideProps
const hasStaticPaths = !!components.getStaticPaths
......@@ -1493,7 +1493,7 @@ export default class Server {
!isLikeServerless &&
!query.amp &&
!this.minimalMode &&
typeof components.Document.getInitialProps !== 'function'
typeof components.Document?.getInitialProps !== 'function'
}
const locale = query.__nextLocale as string
......@@ -1626,7 +1626,7 @@ export default class Server {
// handle serverless
if (isLikeServerless) {
const renderResult = await (
components.Component as any
components.ComponentMod as any
).renderReqToHTML(req, res, 'passthrough', {
locale,
locales,
......
......@@ -2,25 +2,8 @@
const notifier = require('node-notifier')
// eslint-disable-next-line import/no-extraneous-dependencies
const { relative, basename, resolve, join } = require('path')
const { Module } = require('module')
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) {
await task
.source(
......@@ -286,7 +269,13 @@ externals['file-loader'] = 'next/dist/compiled/file-loader'
export async function ncc_file_loader(task, opts) {
await task
.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')
}
// eslint-disable-next-line camelcase
......@@ -600,32 +589,33 @@ export async function ncc_sass_loader(task, opts) {
},
externals: {
...externals,
'schema-utils': 'next/dist/compiled/schema-utils3',
'schema-utils': externals['schema-utils3'],
},
target: 'es5',
})
.target('compiled/sass-loader')
}
// eslint-disable-next-line camelcase
externals['schema-utils'] = 'next/dist/compiled/schema-utils'
export async function ncc_schema_utils(task, opts) {
externals['schema-utils'] = 'MISSING_VERSION schema-utils version not specified'
externals['schema-utils2'] = 'next/dist/compiled/schema-utils2'
export async function ncc_schema_utils2(task, opts) {
await task
.source(opts.src || relative(__dirname, require.resolve('schema-utils')))
.source(opts.src || relative(__dirname, require.resolve('schema-utils2')))
.ncc({
packageName: 'schema-utils',
bundleName: 'schema-utils2',
externals,
})
.target('compiled/schema-utils')
.target('compiled/schema-utils2')
}
// eslint-disable-next-line camelcase
externals['schema-utils3'] = 'next/dist/compiled/schema-utils3'
export async function ncc_schema_utils3(task, opts) {
await task
.source(
opts.src || relative(__dirname, bundleRequire.resolve('schema-utils3'))
)
.source(opts.src || relative(__dirname, require.resolve('schema-utils3')))
.ncc({
packageName: 'schema-utils3',
packageName: 'schema-utils',
bundleName: 'schema-utils3',
externals,
})
.target('compiled/schema-utils3')
......@@ -712,19 +702,22 @@ export async function ncc_web_vitals(task, opts) {
.target('compiled/web-vitals')
}
// eslint-disable-next-line camelcase
externals['webpack-sources'] = 'next/dist/compiled/webpack-sources'
export async function ncc_webpack_sources(task, opts) {
externals['webpack-sources'] = 'error webpack-sources version not specified'
externals['webpack-sources1'] = 'next/dist/compiled/webpack-sources1'
export async function ncc_webpack_sources1(task, opts) {
await task
.source(opts.src || relative(__dirname, require.resolve('webpack-sources')))
.ncc({ packageName: 'webpack-sources', externals, target: 'es5' })
.target('compiled/webpack-sources')
.source(
opts.src || relative(__dirname, require.resolve('webpack-sources1'))
)
.ncc({ packageName: 'webpack-sources1', externals, target: 'es5' })
.target('compiled/webpack-sources1')
}
// eslint-disable-next-line camelcase
externals['webpack-sources3'] = 'next/dist/compiled/webpack-sources3'
export async function ncc_webpack_sources3(task, opts) {
await task
.source(
opts.src || relative(__dirname, bundleRequire.resolve('webpack-sources3'))
opts.src || relative(__dirname, require.resolve('webpack-sources3'))
)
.ncc({ packageName: 'webpack-sources3', externals, target: 'es5' })
.target('compiled/webpack-sources3')
......@@ -745,6 +738,7 @@ export async function ncc_mini_css_extract_plugin(task, opts) {
...externals,
'./index': './index.js',
'schema-utils': 'next/dist/compiled/schema-utils3',
'webpack-sources': externals['webpack-sources1'],
},
})
.target('compiled/mini-css-extract-plugin')
......@@ -758,7 +752,7 @@ export async function ncc_mini_css_extract_plugin(task, opts) {
externals: {
...externals,
'./index': './index.js',
'schema-utils': 'next/dist/compiled/schema-utils3',
'schema-utils': externals['schema-utils3'],
},
})
.target('compiled/mini-css-extract-plugin')
......@@ -768,6 +762,8 @@ export async function ncc_mini_css_extract_plugin(task, opts) {
export async function ncc_webpack_bundle4(task, opts) {
const bundleExternals = {
...externals,
'schema-utils': externals['schema-utils2'],
'webpack-sources': externals['webpack-sources1'],
}
for (const pkg of Object.keys(webpackBundlePackages)) {
delete bundleExternals[pkg]
......@@ -775,7 +771,7 @@ export async function ncc_webpack_bundle4(task, opts) {
await task
.source(opts.src || 'bundles/webpack/bundle4.js')
.ncc({
packageName: 'webpack',
packageName: 'webpack4',
bundleName: 'webpack',
externals: bundleExternals,
minify: false,
......@@ -788,6 +784,8 @@ export async function ncc_webpack_bundle4(task, opts) {
export async function ncc_webpack_bundle5(task, opts) {
const bundleExternals = {
...externals,
'schema-utils': externals['schema-utils3'],
'webpack-sources': externals['webpack-sources3'],
}
for (const pkg of Object.keys(webpackBundlePackages)) {
delete bundleExternals[pkg]
......@@ -800,11 +798,7 @@ export async function ncc_webpack_bundle5(task, opts) {
customEmit(path) {
if (path.endsWith('.runtime.js')) return `'./${basename(path)}'`
},
externals: {
...bundleExternals,
'schema-utils': 'next/dist/compiled/schema-utils3',
'webpack-sources': 'next/dist/compiled/webpack-sources3',
},
externals: bundleExternals,
minify: false,
target: 'es5',
})
......@@ -814,6 +808,8 @@ export async function ncc_webpack_bundle5(task, opts) {
const webpackBundlePackages = {
webpack: 'next/dist/compiled/webpack/webpack-lib',
'webpack/lib/NormalModule': 'next/dist/compiled/webpack/NormalModule',
'webpack/lib/node/NodeTargetPlugin':
'next/dist/compiled/webpack/NodeTargetPlugin',
}
Object.assign(externals, webpackBundlePackages)
......@@ -899,7 +895,7 @@ export async function ncc(task, opts) {
'ncc_icss_utils',
'ncc_resolve_url_loader',
'ncc_sass_loader',
'ncc_schema_utils',
'ncc_schema_utils2',
'ncc_schema_utils3',
'ncc_semver',
'ncc_send',
......@@ -914,7 +910,7 @@ export async function ncc(task, opts) {
'ncc_webpack_bundle4',
'ncc_webpack_bundle5',
'ncc_webpack_bundle_packages',
'ncc_webpack_sources',
'ncc_webpack_sources1',
'ncc_webpack_sources3',
'ncc_mini_css_extract_plugin',
],
......
......@@ -225,7 +225,7 @@ declare module 'next/dist/compiled/comment-json' {
}
declare module 'pnp-webpack-plugin' {
import webpack from 'webpack'
import webpack from 'webpack4'
class PnpWebpackPlugin extends webpack.Plugin {}
......
......@@ -27,20 +27,40 @@ declare module 'mini-css-extract-plugin'
declare module 'next/dist/compiled/loader-utils'
declare module 'next/dist/compiled/webpack/webpack' {
import webpackSources from 'webpack-sources'
import webpack, { loader } from 'webpack'
import webpackSources from 'webpack-sources1'
import webpack4, { loader } from 'webpack4'
export { NormalModule } from 'webpack'
export let isWebpack5: boolean
export function init(useWebpack5: boolean): void
export let BasicEvaluatedExpression: any
export let GraphHelpers: any
export function onWebpackInit(cb: () => void): void
// TODO change this to webpack4 | webpack5
export let sources: typeof webpackSources
export { webpack, loader }
// TODO change this to webpack
export { webpack4 as webpack, loader }
}
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 { ConcatSource } from 'webpack-sources'
import { ConcatSource } from 'webpack-sources1'
export = webpack
......
......@@ -11,7 +11,7 @@ import { StackFrame } from 'stacktrace-parser'
import url from 'url'
// @ts-ignore
// eslint-disable-next-line import/no-extraneous-dependencies
import webpack from 'webpack'
import type webpack from 'webpack4'
import { getRawSourceMap } from './internal/helpers/getRawSourceMap'
import { launchEditor } from './internal/helpers/launchEditor'
......
// types only import
import {
Compiler as WebpackCompiler,
Template as WebpackTemplate,
// @ts-ignore exists in webpack 5
RuntimeModule as WebpackRuntimeModule,
// @ts-ignore exists in webpack 5
RuntimeGlobals as WebpackRuntimeGlobals,
// @ts-ignore exists in webpack 5
compilation as WebpackCompilation,
Compilation as WebpackCompilation,
} from 'webpack'
// Shared between webpack 4 and 5:
function injectRefreshFunctions(
compilation: WebpackCompilation.Compilation,
compilation: WebpackCompilation,
Template: typeof WebpackTemplate
) {
const hookVars: any = (compilation.mainTemplate.hooks as any).localVars
......@@ -97,7 +93,6 @@ function webpack5(this: ReactFreshWebpackPlugin, compiler: WebpackCompiler) {
}
generate() {
// @ts-ignore This exists in webpack 5
const { runtimeTemplate } = this.compilation
return Template.asString([
`if (${RuntimeGlobals.interceptModuleExecution}) {`,
......
import {
// @ts-ignore exists in webpack 5
loader,
} from 'webpack'
import type { LoaderDefinition } from 'webpack'
import RefreshModuleRuntime from './internal/ReactRefreshModule.runtime'
let refreshModuleRuntime = RefreshModuleRuntime.toString()
......@@ -10,7 +7,7 @@ refreshModuleRuntime = refreshModuleRuntime.slice(
refreshModuleRuntime.lastIndexOf('}')
)
const ReactRefreshLoader: loader.Loader = function ReactRefreshLoader(
const ReactRefreshLoader: LoaderDefinition = function ReactRefreshLoader(
source,
inputSourceMap
) {
......
......@@ -6,7 +6,10 @@
"target": "es2015",
"lib": ["dom"],
"downlevelIteration": true,
"preserveWatchOutput": true
"preserveWatchOutput": true,
"paths": {
"webpack": ["../../node_modules/webpack5"]
}
},
"include": ["**/*.ts"],
"exclude": ["node_modules"]
......
#!/bin/bash
yarn --cwd packages/next/bundles
cp packages/next/bundles/node_modules/webpack5/lib/hmr/HotModuleReplacement.runtime.js packages/next/bundles/webpack/packages/
cp packages/next/bundles/node_modules/webpack5/lib/hmr/JavascriptHotModuleReplacement.runtime.js packages/next/bundles/webpack/packages/
cp 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/
yarn --cwd packages/next 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
if [[ ! -z $(git status -s) ]];then
echo "Detected changes"
git status
git diff -a --stat
exit 1
fi
module.exports = {
// target: 'experimental-serverless-trace',
webpack: (config, options) => {
config.experiments = {
topLevelAwait: true,
}
webpack: (config) => {
config.experiments = config.experiments || {}
config.experiments.topLevelAwait = true
return config
},
}
import Head from 'next/head'
export const config = {
amp: true,
}
......@@ -8,6 +10,14 @@ export default function Config() {
const date = new Date()
return (
<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
id="amp-timeago"
width="0"
......
......@@ -12,11 +12,10 @@ import {
nextBuild,
nextStart,
File,
check,
} from 'next-test-utils'
import { join } from 'path'
import webpack from 'webpack'
const isWebpack5 = parseInt(webpack.version) === 5
let app
let appPort
const appDir = join(__dirname, '../')
......@@ -83,7 +82,11 @@ function runTests(dev = false) {
let browser
try {
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 {
if (browser) await browser.close()
}
......@@ -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', () => {
beforeAll(async () => {
appPort = await findPort()
......
......@@ -5,17 +5,10 @@ import { findPort, killApp, launchApp, nextBuild } from 'next-test-utils'
import webdriver from 'next-webdriver'
import { recursiveReadDir } from 'next/dist/lib/recursive-readdir'
import { join } from 'path'
import { version } from 'webpack'
const isWebpack5 = parseInt(version) === 5
const appDir = join(__dirname, '../')
// TODO: Make legacy Sass support work with webpack 5
const describeFn = isWebpack5 ? describe.skip : describe
// TODO: Make legacy Sass support work with webpack 5
describeFn('Legacy Sass Support Should Disable New CSS', () => {
describe('Legacy Sass Support Should Disable New CSS', () => {
beforeAll(async () => {
await remove(join(appDir, '.next'))
await nextBuild(appDir)
......@@ -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 () => {
await remove(join(appDir, '.next'))
})
......
......@@ -3,30 +3,25 @@
import webdriver from 'next-webdriver'
import { join } from 'path'
import {
nextServer,
nextStart,
nextBuild,
startApp,
stopApp,
findPort,
killApp,
runNextCommand,
} from 'next-test-utils'
const appDir = join(__dirname, '../')
let app
let appPort
let server
describe('Production Config Usage', () => {
beforeAll(async () => {
await nextBuild(appDir)
const app = nextServer({
dir: join(__dirname, '../'),
dev: false,
quiet: true,
})
server = await startApp(app)
appPort = server.address().port
appPort = await findPort()
app = await nextStart(appDir, appPort)
})
afterAll(() => stopApp(server))
afterAll(() => killApp(app))
describe('with next-css', () => {
it('should load styles', async () => {
......
......@@ -17,6 +17,7 @@ export class NextInstance {
protected dependencies?: { [name: string]: string }
protected events: { [eventName: string]: Set<any> }
protected testDir: string
protected isStopping: boolean
protected isDestroyed: boolean
protected childProcess: ChildProcess
protected _url: string
......@@ -40,6 +41,7 @@ export class NextInstance {
this.nextConfig = nextConfig
this.events = {}
this.isDestroyed = false
this.isStopping = false
}
protected async createTestDir() {
......@@ -120,6 +122,7 @@ export class NextInstance {
public async setup(): Promise<void> {}
public async start(): Promise<void> {}
public async stop(): Promise<void> {
this.isStopping = true
if (this.childProcess) {
let exitResolve
const exitPromise = new Promise((resolve) => {
......
......@@ -49,6 +49,7 @@ export class NextDevInstance extends NextInstance {
})
this.childProcess.on('close', (code) => {
if (this.isStopping) return
if (code) {
throw new Error(`next dev exited unexpectedly with code ${code}`)
}
......
......@@ -81,6 +81,13 @@ export class NextStartInstance extends NextInstance {
)
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) => {
const readyCb = (msg) => {
if (msg.includes('started server on') && msg.includes('url:')) {
......
......@@ -10,9 +10,6 @@ import {
import { writeFile } from 'fs-extra'
import getPort from 'get-port'
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 _pkg from 'next/package.json'
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