Skip to content

Commit

Permalink
webpack inlining
Browse files Browse the repository at this point in the history
  • Loading branch information
guybedford committed Jan 13, 2021
1 parent e1184fb commit 099cd30
Show file tree
Hide file tree
Showing 48 changed files with 801 additions and 322 deletions.
14 changes: 10 additions & 4 deletions packages/next/build/compiler.ts
@@ -1,11 +1,14 @@
import webpack, { Stats, Configuration } from 'webpack'
import webpack from 'next/dist/compiled/webpack/webpack'

export type CompilerResult = {
errors: string[]
warnings: string[]
}

function generateStats(result: CompilerResult, stat: Stats): CompilerResult {
function generateStats(
result: CompilerResult,
stat: webpack.Stats
): CompilerResult {
const { errors, warnings } = stat.toJson('errors-warnings')
if (errors.length > 0) {
result.errors.push(...errors)
Expand All @@ -32,12 +35,15 @@ function closeCompiler(compiler: webpack.Compiler | webpack.MultiCompiler) {
}

export function runCompiler(
config: Configuration | Configuration[]
config: webpack.Configuration | webpack.Configuration[]
): Promise<CompilerResult> {
return new Promise((resolve, reject) => {
const compiler = webpack(config)
compiler.run(
(err: Error, statsOrMultiStats: { stats: Stats[] } | Stats) => {
(
err: Error,
statsOrMultiStats: { stats: webpack.Stats[] } | webpack.Stats
) => {
closeCompiler(compiler).then(() => {
if (err) {
const reason = err?.toString()
Expand Down
38 changes: 19 additions & 19 deletions packages/next/build/webpack-config.ts
Expand Up @@ -7,8 +7,11 @@ import semver from 'next/dist/compiled/semver'
// @ts-ignore No typings yet
import TerserPlugin from './webpack/plugins/terser-webpack-plugin/src/index.js'
import path from 'path'
import webpack from 'webpack'
import { Configuration } from 'webpack'
import webpack, {
isWebpack5,
init as initWebpack,
} from 'next/dist/compiled/webpack/webpack'
// eslint-disable-next-line import/no-extraneous-dependencies
import {
DOT_NEXT_ALIAS,
NEXT_PROJECT_ROOT,
Expand Down Expand Up @@ -61,23 +64,16 @@ import { NextConfig } from '../next-server/server/config'

type ExcludesFalse = <T>(x: T | false) => x is T

const isWebpack5 = parseInt(webpack.version!) === 5

if (isWebpack5 && semver.lt(webpack.version!, '5.11.1')) {
Log.error(
`webpack 5 version must be greater than v5.11.1 to work properly with Next.js, please upgrade to continue!\nSee more info here: https://err.sh/next.js/invalid-webpack-5-version`
)
process.exit(1)
}

const devtoolRevertWarning = execOnce((devtool: Configuration['devtool']) => {
console.warn(
chalk.yellow.bold('Warning: ') +
chalk.bold(`Reverting webpack devtool to '${devtool}'.\n`) +
'Changing the webpack devtool in development mode will cause severe performance regressions.\n' +
'Read more: https://err.sh/next.js/improper-devtool'
)
})
const devtoolRevertWarning = execOnce(
(devtool: webpack.Configuration['devtool']) => {
console.warn(
chalk.yellow.bold('Warning: ') +
chalk.bold(`Reverting webpack devtool to '${devtool}'.\n`) +
'Changing the webpack devtool in development mode will cause severe performance regressions.\n' +
'Read more: https://err.sh/next.js/improper-devtool'
)
}
)

function parseJsonFile(filePath: string) {
const JSON5 = require('next/dist/compiled/json5')
Expand Down Expand Up @@ -196,6 +192,7 @@ export default async function getBaseWebpackConfig(
reactProductionProfiling = false,
entrypoints,
rewrites,
webpack5 = false,
}: {
buildId: string
config: NextConfig
Expand All @@ -206,8 +203,11 @@ export default async function getBaseWebpackConfig(
reactProductionProfiling?: boolean
entrypoints: WebpackEntrypoints
rewrites: Rewrite[]
webpack5: boolean
}
): Promise<webpack.Configuration> {
initWebpack(webpack5)

let plugins: PluginMetaData[] = []
let babelPresetPlugins: { dir: string; config: any }[] = []

Expand Down
4 changes: 2 additions & 2 deletions packages/next/build/webpack/config/blocks/base.ts
@@ -1,13 +1,13 @@
import isWslBoolean from 'next/dist/compiled/is-wsl'
import curry from 'next/dist/compiled/lodash.curry'
import { Configuration } from 'webpack'
import webpack from 'next/dist/compiled/webpack/webpack'
import { ConfigurationContext } from '../utils'

const isWindows = process.platform === 'win32' || isWslBoolean

export const base = curry(function base(
ctx: ConfigurationContext,
config: Configuration
config: webpack.Configuration
) {
config.mode = ctx.isDevelopment ? 'development' : 'production'
config.name = ctx.isServer ? 'server' : 'client'
Expand Down
4 changes: 2 additions & 2 deletions packages/next/build/webpack/config/blocks/css/index.ts
@@ -1,6 +1,6 @@
import curry from 'next/dist/compiled/lodash.curry'
import path from 'path'
import webpack, { Configuration } from 'webpack'
import webpack from 'next/dist/compiled/webpack/webpack'
import MiniCssExtractPlugin from '../../../plugins/mini-css-extract-plugin'
import { loader, plugin } from '../../helpers'
import { ConfigurationContext, ConfigurationFn, pipe } from '../../utils'
Expand All @@ -26,7 +26,7 @@ const regexSassModules = /\.module\.(scss|sass)$/

export const css = curry(async function css(
ctx: ConfigurationContext,
config: Configuration
config: webpack.Configuration
) {
const {
prependData: sassPrependData,
Expand Down
@@ -1,4 +1,4 @@
import webpack from 'webpack'
import webpack from 'next/dist/compiled/webpack/webpack'
import MiniCssExtractPlugin from '../../../../plugins/mini-css-extract-plugin'

export function getClientStyleLoader({
Expand Down
@@ -1,6 +1,6 @@
import loaderUtils from 'loader-utils'
import path from 'path'
import webpack from 'webpack'
import webpack from 'next/dist/compiled/webpack/webpack'

const regexLikeIndexModule = /(?<!pages[\\/])index\.module\.(scss|sass|css)$/

Expand Down
@@ -1,5 +1,5 @@
import { AcceptedPlugin } from 'postcss'
import webpack from 'webpack'
import webpack from 'next/dist/compiled/webpack/webpack'
import { ConfigurationContext } from '../../../utils'
import { getClientStyleLoader } from './client'
import { cssFileResolve } from './file-resolve'
Expand Down
@@ -1,5 +1,5 @@
import { AcceptedPlugin } from 'postcss'
import webpack from 'webpack'
import webpack from 'next/dist/compiled/webpack/webpack'
import { ConfigurationContext } from '../../../utils'
import { getClientStyleLoader } from './client'
import { cssFileResolve } from './file-resolve'
Expand Down
@@ -1,14 +1,14 @@
import { Configuration, RuleSetRule } from 'webpack'
import webpack from 'next/dist/compiled/webpack/webpack'
import { getPostCssPlugins } from './plugins'

export async function __overrideCssConfiguration(
rootDirectory: string,
isProduction: boolean,
config: Configuration
config: webpack.Configuration
) {
const postCssPlugins = await getPostCssPlugins(rootDirectory, isProduction)

function patch(rule: RuleSetRule) {
function patch(rule: webpack.RuleSetRule) {
if (
rule.options &&
typeof rule.options === 'object' &&
Expand Down
15 changes: 9 additions & 6 deletions packages/next/build/webpack/config/helpers.ts
@@ -1,9 +1,9 @@
import curry from 'next/dist/compiled/lodash.curry'
import { Configuration, Plugin, RuleSetRule } from 'webpack'
import webpack from 'next/dist/compiled/webpack/webpack'

export const loader = curry(function loader(
rule: RuleSetRule,
config: Configuration
rule: webpack.RuleSetRule,
config: webpack.Configuration
) {
if (!config.module) {
config.module = { rules: [] }
Expand All @@ -22,8 +22,8 @@ export const loader = curry(function loader(
})

export const unshiftLoader = curry(function unshiftLoader(
rule: RuleSetRule,
config: Configuration
rule: webpack.RuleSetRule,
config: webpack.Configuration
) {
if (!config.module) {
config.module = { rules: [] }
Expand All @@ -41,7 +41,10 @@ export const unshiftLoader = curry(function unshiftLoader(
return config
})

export const plugin = curry(function plugin(p: Plugin, config: Configuration) {
export const plugin = curry(function plugin(
p: webpack.Plugin,
config: webpack.Configuration
) {
if (!config.plugins) {
config.plugins = []
}
Expand Down
2 changes: 1 addition & 1 deletion packages/next/build/webpack/config/index.ts
@@ -1,4 +1,4 @@
import webpack from 'webpack'
import webpack from 'next/dist/compiled/webpack/webpack'
import { NextConfig } from '../../../next-server/server/config'
import { base } from './blocks/base'
import { css } from './blocks/css'
Expand Down
2 changes: 1 addition & 1 deletion packages/next/build/webpack/config/utils.ts
@@ -1,4 +1,4 @@
import webpack from 'webpack'
import webpack from 'next/dist/compiled/webpack/webpack'
import { NextConfig } from '../../../next-server/server/config'

export type ConfigurationContext = {
Expand Down
4 changes: 2 additions & 2 deletions packages/next/build/webpack/loaders/error-loader.ts
@@ -1,9 +1,9 @@
import chalk from 'chalk'
import loaderUtils from 'loader-utils'
import path from 'path'
import { loader } from 'webpack'
import webpack from 'next/dist/compiled/webpack/webpack'

const ErrorLoader: loader.Loader = function () {
const ErrorLoader: webpack.loader.Loader = function () {
const options = loaderUtils.getOptions(this) || {}

const { reason = 'An unknown error has occurred' } = options
Expand Down
4 changes: 2 additions & 2 deletions packages/next/build/webpack/loaders/next-plugin-loader.ts
@@ -1,4 +1,4 @@
import { loader } from 'webpack'
import webpack from 'next/dist/compiled/webpack/webpack'
import { parse } from 'querystring'
import { PluginMetaData, getPluginId } from '../../plugins/collect-plugins'

Expand All @@ -12,7 +12,7 @@ export const pluginLoaderOptions: {
plugins: [],
}

const nextPluginLoader: loader.Loader = function () {
const nextPluginLoader: webpack.loader.Loader = function () {
const { middleware }: NextPluginLoaderQuery =
typeof this.query === 'string' ? parse(this.query.substr(1)) : this.query

Expand Down
Expand Up @@ -2,7 +2,7 @@ import devalue from 'next/dist/compiled/devalue'
import escapeRegexp from 'next/dist/compiled/escape-string-regexp'
import { join } from 'path'
import { parse } from 'querystring'
import { loader } from 'webpack'
import webpack from 'next/dist/compiled/webpack/webpack'
import { API_ROUTE } from '../../../../lib/constants'
import { isDynamicRoute } from '../../../../next-server/lib/router/utils'
import { __ApiPreviewProps } from '../../../../next-server/server/api-utils'
Expand Down Expand Up @@ -33,7 +33,7 @@ export type ServerlessLoaderQuery = {
i18n: string
}

const nextServerlessLoader: loader.Loader = function () {
const nextServerlessLoader: webpack.loader.Loader = function () {
const span = tracer.startSpan('next-serverless-loader')
return traceFn(span, () => {
const {
Expand Down
4 changes: 2 additions & 2 deletions packages/next/build/webpack/loaders/noop-loader.ts
@@ -1,4 +1,4 @@
import { loader } from 'webpack'
import webpack from 'next/dist/compiled/webpack/webpack'

const NoopLoader: loader.Loader = (source) => source
const NoopLoader: webpack.loader.Loader = (source) => source
export default NoopLoader
16 changes: 10 additions & 6 deletions packages/next/build/webpack/plugins/build-manifest-plugin.ts
@@ -1,5 +1,8 @@
import devalue from 'next/dist/compiled/devalue'
import webpack, { Compiler, compilation as CompilationType } from 'webpack'
import webpack, {
isWebpack5,
onWebpackInit,
} from 'next/dist/compiled/webpack/webpack'
import sources from 'webpack-sources'
import {
BUILD_MANIFEST,
Expand All @@ -17,9 +20,10 @@ import { getSortedRoutes } from '../../../next-server/lib/router/utils'
import { tracer, traceFn } from '../../tracer'
import { spans } from './profiling-plugin'
// @ts-ignore: TODO: remove ignore when webpack 5 is stable
const { RawSource } = webpack.sources || sources

const isWebpack5 = parseInt(webpack.version!) === 5
let RawSource: typeof sources.RawSource
onWebpackInit(function () {
;({ RawSource } = (webpack as any).sources || sources)
})

type DeepMutable<T> = { -readonly [P in keyof T]: DeepMutable<T[P]> }

Expand Down Expand Up @@ -107,7 +111,7 @@ export default class BuildManifestPlugin {
return tracer.withSpan(spans.get(compiler), () => {
const span = tracer.startSpan('NextJsBuildManifest-createassets')
return traceFn(span, () => {
const namedChunks: Map<string, CompilationType.Chunk> =
const namedChunks: Map<string, webpack.compilation.Chunk> =
compilation.namedChunks
const assetMap: DeepMutable<BuildManifest> = {
polyfillFiles: [],
Expand Down Expand Up @@ -226,7 +230,7 @@ export default class BuildManifestPlugin {
})
}

apply(compiler: Compiler) {
apply(compiler: webpack.Compiler) {
if (isWebpack5) {
compiler.hooks.make.tap('NextJsBuildManifest', (compilation) => {
// @ts-ignore TODO: Remove ignore when webpack 5 is stable
Expand Down
4 changes: 2 additions & 2 deletions packages/next/build/webpack/plugins/chunk-names-plugin.ts
@@ -1,9 +1,9 @@
import { Compiler } from 'webpack'
import webpack from 'next/dist/compiled/webpack/webpack'
// This plugin mirrors webpack 3 `filename` and `chunkfilename` behavior
// This fixes https://github.com/webpack/webpack/issues/6598
// This plugin is based on https://github.com/researchgate/webpack/commit/2f28947fa0c63ccbb18f39c0098bd791a2c37090
export default class ChunkNamesPlugin {
apply(compiler: Compiler) {
apply(compiler: webpack.Compiler) {
compiler.hooks.compilation.tap(
'NextJsChunkNamesPlugin',
(compilation: any) => {
Expand Down
13 changes: 9 additions & 4 deletions packages/next/build/webpack/plugins/css-minimizer-plugin.ts
@@ -1,13 +1,20 @@
import cssnanoSimple from 'cssnano-simple'
import postcssScss from 'next/dist/compiled/postcss-scss'
import postcss, { Parser } from 'postcss'
import webpack from 'webpack'
import webpack, {
isWebpack5,
onWebpackInit,
} from 'next/dist/compiled/webpack/webpack'
import sources from 'webpack-sources'
import { tracer, traceAsyncFn } from '../../tracer'
import { spans } from './profiling-plugin'

// @ts-ignore: TODO: remove ignore when webpack 5 is stable
const { RawSource, SourceMapSource } = webpack.sources || sources
let RawSource: typeof sources.RawSource,
SourceMapSource: typeof sources.SourceMapSource
onWebpackInit(function () {
;({ RawSource, SourceMapSource } = (webpack as any).sources || sources)
})

// https://github.com/NMFR/optimize-css-assets-webpack-plugin/blob/0a410a9bf28c7b0e81a3470a13748e68ca2f50aa/src/index.js#L20
const CSS_REGEX = /\.css(\?.*)?$/i
Expand All @@ -18,8 +25,6 @@ type CssMinimizerPluginOptions = {
}
}

const isWebpack5 = parseInt(webpack.version!) === 5

export class CssMinimizerPlugin {
__next_css_remove = true

Expand Down

0 comments on commit 099cd30

Please sign in to comment.