Unverified Commit fe09c103 authored by Joe Haddad's avatar Joe Haddad Committed by GitHub

Upgrade `terser-webpack-plugin` for Webpack 5 (#11922)

* Upgrade `terser-webpack-plugin` for Webpack 5

* Upgrade again

* cacache cannot be bundled

* cacache cannot be bundled

* fix file

* remove cacache dep

* Update LICENSE
parent 92dac596
import chalk from 'next/dist/compiled/chalk'
import crypto from 'crypto' import crypto from 'crypto'
import ForkTsCheckerWebpackPlugin from 'fork-ts-checker-webpack-plugin' import ForkTsCheckerWebpackPlugin from 'fork-ts-checker-webpack-plugin'
import { readFileSync } from 'fs'
import chalk from 'next/dist/compiled/chalk'
import TerserPlugin from 'next/dist/compiled/terser-webpack-plugin'
import path from 'path' import path from 'path'
import PnpWebpackPlugin from 'pnp-webpack-plugin' import PnpWebpackPlugin from 'pnp-webpack-plugin'
import { MinifyOptions } from 'terser'
import webpack from 'webpack' import webpack from 'webpack'
import { import {
DOT_NEXT_ALIAS, DOT_NEXT_ALIAS,
...@@ -11,7 +14,6 @@ import { ...@@ -11,7 +14,6 @@ import {
PAGES_DIR_ALIAS, PAGES_DIR_ALIAS,
} from '../lib/constants' } from '../lib/constants'
import { fileExists } from '../lib/file-exists' import { fileExists } from '../lib/file-exists'
import { readFileSync } from 'fs'
import { resolveRequest } from '../lib/resolve-request' import { resolveRequest } from '../lib/resolve-request'
import { import {
CLIENT_STATIC_FILES_RUNTIME_MAIN, CLIENT_STATIC_FILES_RUNTIME_MAIN,
...@@ -34,6 +36,7 @@ import { pluginLoaderOptions } from './webpack/loaders/next-plugin-loader' ...@@ -34,6 +36,7 @@ import { pluginLoaderOptions } from './webpack/loaders/next-plugin-loader'
import BuildManifestPlugin from './webpack/plugins/build-manifest-plugin' import BuildManifestPlugin from './webpack/plugins/build-manifest-plugin'
import ChunkNamesPlugin from './webpack/plugins/chunk-names-plugin' import ChunkNamesPlugin from './webpack/plugins/chunk-names-plugin'
import { CssMinimizerPlugin } from './webpack/plugins/css-minimizer-plugin' import { CssMinimizerPlugin } from './webpack/plugins/css-minimizer-plugin'
import { JsConfigPathsPlugin } from './webpack/plugins/jsconfig-paths-plugin'
import { DropClientPage } from './webpack/plugins/next-drop-client-page-plugin' import { DropClientPage } from './webpack/plugins/next-drop-client-page-plugin'
import NextEsmPlugin from './webpack/plugins/next-esm-plugin' import NextEsmPlugin from './webpack/plugins/next-esm-plugin'
import NextJsSsrImportPlugin from './webpack/plugins/nextjs-ssr-import' import NextJsSsrImportPlugin from './webpack/plugins/nextjs-ssr-import'
...@@ -42,12 +45,10 @@ import PagesManifestPlugin from './webpack/plugins/pages-manifest-plugin' ...@@ -42,12 +45,10 @@ import PagesManifestPlugin from './webpack/plugins/pages-manifest-plugin'
import { ProfilingPlugin } from './webpack/plugins/profiling-plugin' import { ProfilingPlugin } from './webpack/plugins/profiling-plugin'
import { ReactLoadablePlugin } from './webpack/plugins/react-loadable-plugin' import { ReactLoadablePlugin } from './webpack/plugins/react-loadable-plugin'
import { ServerlessPlugin } from './webpack/plugins/serverless-plugin' import { ServerlessPlugin } from './webpack/plugins/serverless-plugin'
import { TerserPlugin } from './webpack/plugins/terser-webpack-plugin/src/index'
import { JsConfigPathsPlugin } from './webpack/plugins/jsconfig-paths-plugin'
import WebpackConformancePlugin, { import WebpackConformancePlugin, {
DuplicatePolyfillsConformanceCheck,
MinificationConformanceCheck, MinificationConformanceCheck,
ReactSyncScriptsConformanceCheck, ReactSyncScriptsConformanceCheck,
DuplicatePolyfillsConformanceCheck,
} from './webpack/plugins/webpack-conformance-plugin' } from './webpack/plugins/webpack-conformance-plugin'
type ExcludesFalse = <T>(x: T | false) => x is T type ExcludesFalse = <T>(x: T | false) => x is T
...@@ -281,15 +282,7 @@ export default async function getBaseWebpackConfig( ...@@ -281,15 +282,7 @@ export default async function getBaseWebpackConfig(
const webpackMode = dev ? 'development' : 'production' const webpackMode = dev ? 'development' : 'production'
const terserPluginConfig = { const terserOptions: MinifyOptions = {
cache: true,
cpus: config.experimental.cpus,
distDir: distDir,
parallel: true,
sourceMap: false,
workerThreads: config.experimental.workerThreads,
}
const terserOptions = {
parse: { parse: {
ecma: 8, ecma: 8,
}, },
...@@ -635,7 +628,8 @@ export default async function getBaseWebpackConfig( ...@@ -635,7 +628,8 @@ export default async function getBaseWebpackConfig(
minimizer: [ minimizer: [
// Minify JavaScript // Minify JavaScript
new TerserPlugin({ new TerserPlugin({
...terserPluginConfig, cache: path.join(distDir, 'cache', 'next-minifier'),
parallel: config.experimental.cpus || true,
terserOptions, terserOptions,
}), }),
// Minify CSS // Minify CSS
......
import { join } from 'path'
import minify from './minify'
import { promisify } from 'util'
import Worker from 'jest-worker'
import { mkdirSync, writeFile, readFile } from 'fs'
const worker = require.resolve('./minify')
const writeFileP = promisify(writeFile)
const readFileP = promisify(readFile)
export default class TaskRunner {
constructor({ distDir, cpus, cache, workerThreads }) {
if (cache) {
mkdirSync((this.cacheDir = join(distDir, 'cache', 'next-minifier')), {
recursive: true,
})
}
// In some cases cpus() returns undefined
// https://github.com/nodejs/node/issues/19022
this.maxConcurrentWorkers = cpus
this.useWorkerThreads = workerThreads
}
run(tasks, callback) {
/* istanbul ignore if */
if (!tasks.length) {
callback(null, [])
return
}
if (this.maxConcurrentWorkers > 1) {
this.workers = new Worker(worker, {
enableWorkerThreads: this.useWorkerThreads,
numWorkers: this.maxConcurrentWorkers,
})
this.boundWorkers = options => this.workers.default(options)
} else {
this.boundWorkers = async options => minify(options)
}
let toRun = tasks.length
const results = []
const step = (index, data) => {
toRun -= 1
results[index] = data
if (!toRun) {
callback(null, results)
}
}
tasks.forEach((task, index) => {
const cachePath = this.cacheDir && join(this.cacheDir, task.cacheKey)
const enqueue = async () => {
try {
const result = await this.boundWorkers(task)
const done = () => step(index, result)
if (cachePath) {
writeFileP(cachePath, JSON.stringify(result), 'utf8')
// This is important to stay as `.then(fn1, fn2)` and not
// `.then(fn1).catch(fn2)` so that we don't double-invoke `step`
// when `done` emits an error.
.then(done, done)
.catch(err => {
// Abort task on internal error (`done` failed). This can
// happen when users have a bad `package-lock.json` with an
// invalid webpack version, etc:
callback(err)
})
}
} catch (error) {
step(index, { error })
}
}
if (this.cacheDir) {
// This is important to stay as `.then(fn1, fn2)` and not
// `.then(fn1).catch(fn2)` so that we don't double-invoke `step` when
// `step` emits an error.
readFileP(cachePath, 'utf8').then(
data => {
try {
step(index, JSON.parse(data))
} catch (err) {
// Abort task on internal error (`done` failed). This can happen
// when users have a bad `package-lock.json` with an invalid
// webpack version, etc:
callback(err)
}
},
() => enqueue()
)
} else {
enqueue()
}
})
}
exit() {
if (this.workers) {
this.workers.end()
}
}
}
export class TerserPlugin {
readonly cpus: any
readonly distDir: any
readonly options: any
constructor(options?: any)
static isSourceMap(input: any): any
static buildSourceMap(inputSourceMap: any): any
static buildError(
err: any,
file: any,
sourceMap: any,
requestShortener?: any
): any
static buildWarning(
warning: any,
file: any,
sourceMap: any,
requestShortener?: any,
warningsFilter?: any
): any
apply(compiler: any): void
}
/* eslint-disable
no-param-reassign
*/
import stringHash from 'next/dist/compiled/string-hash'
import { SourceMapConsumer } from 'next/dist/compiled/source-map'
import { SourceMapSource, RawSource } from 'webpack-sources'
import RequestShortener from 'webpack/lib/RequestShortener'
import TaskRunner from './TaskRunner'
const warningRegex = /\[.+:([0-9]+),([0-9]+)\]/
const JS_REGEX = /\.m?js$/
export class TerserPlugin {
constructor(options = {}) {
const {
terserOptions = {},
warningsFilter = () => true,
sourceMap = false,
cache = false,
cpus,
distDir,
workerThreads,
} = options
this.cpus = cpus
this.distDir = distDir
this.workerThreads = workerThreads
this.options = {
warningsFilter,
sourceMap,
cache,
terserOptions,
}
}
static isSourceMap(input) {
// All required options for `new SourceMapConsumer(...options)`
// https://github.com/mozilla/source-map#new-sourcemapconsumerrawsourcemap
return Boolean(
input &&
input.version &&
input.sources &&
Array.isArray(input.sources) &&
typeof input.mappings === 'string'
)
}
static buildSourceMap(inputSourceMap) {
if (!inputSourceMap || !TerserPlugin.isSourceMap(inputSourceMap)) {
return null
}
return new SourceMapConsumer(inputSourceMap)
}
static buildError(err, file, sourceMap, requestShortener) {
// Handling error which should have line, col, filename and message
if (err.line) {
const original =
sourceMap &&
sourceMap.originalPositionFor({
line: err.line,
column: err.col,
})
if (original && original.source && requestShortener) {
return new Error(
`${file} from Terser\n${err.message} [${requestShortener.shorten(
original.source
)}:${original.line},${original.column}][${file}:${err.line},${
err.col
}]`
)
}
return new Error(
`${file} from Terser\n${err.message} [${file}:${err.line},${err.col}]`
)
} else if (err.stack) {
return new Error(`${file} from Terser\n${err.stack}`)
}
return new Error(`${file} from Terser\n${err.message}`)
}
static buildWarning(
warning,
file,
sourceMap,
requestShortener,
warningsFilter
) {
let warningMessage = warning
let locationMessage = ''
let source = null
if (sourceMap) {
const match = warningRegex.exec(warning)
if (match) {
const line = +match[1]
const column = +match[2]
const original = sourceMap.originalPositionFor({
line,
column,
})
if (
original &&
original.source &&
original.source !== file &&
requestShortener
) {
;({ source } = original)
warningMessage = `${warningMessage.replace(warningRegex, '')}`
locationMessage = `[${requestShortener.shorten(original.source)}:${
original.line
},${original.column}]`
}
}
}
if (warningsFilter && !warningsFilter(warning, source)) {
return null
}
return `Terser Plugin: ${warningMessage}${locationMessage}`
}
apply(compiler) {
const optimizeFn = (compilation, chunks, callback) => {
const taskRunner = new TaskRunner({
distDir: this.distDir,
cpus: this.cpus,
cache: this.options.cache,
workerThreads: this.workerThreads,
})
const processedAssets = new WeakSet()
const tasks = []
Array.from(chunks)
.reduce((acc, chunk) => acc.concat(chunk.files || []), [])
.concat(compilation.additionalChunkAssets || [])
.filter(file => JS_REGEX.test(file))
.forEach(file => {
let inputSourceMap
const asset = compilation.assets[file]
if (processedAssets.has(asset)) {
return
}
try {
let input
if (this.options.sourceMap && asset.sourceAndMap) {
const { source, map } = asset.sourceAndMap()
input = source
if (TerserPlugin.isSourceMap(map)) {
inputSourceMap = map
} else {
inputSourceMap = map
compilation.warnings.push(
new Error(`${file} contains invalid source map`)
)
}
} else {
input = asset.source()
inputSourceMap = null
}
const task = {
file,
input,
inputSourceMap,
terserOptions: this.options.terserOptions,
}
if (this.options.cache) {
// increment 'a' to invalidate previous caches from different options
task.cacheKey = 'a' + stringHash(input)
if (this.options.sourceMap) task.cacheKey += 's'
}
tasks.push(task)
} catch (error) {
compilation.errors.push(
TerserPlugin.buildError(
error,
file,
TerserPlugin.buildSourceMap(inputSourceMap),
new RequestShortener(compiler.context)
)
)
}
})
taskRunner.run(tasks, (tasksError, results) => {
if (tasksError) {
try {
taskRunner.exit()
} finally {
callback(tasksError)
}
return
}
results.forEach((data, index) => {
const { file, input, inputSourceMap } = tasks[index]
const { error, map, code, warnings } = data
let sourceMap = null
if (error || (warnings && warnings.length > 0)) {
sourceMap = TerserPlugin.buildSourceMap(inputSourceMap)
}
// Handling results
// Error case: add errors, and go to next file
if (error) {
compilation.errors.push(
TerserPlugin.buildError(
error,
file,
sourceMap,
new RequestShortener(compiler.context)
)
)
return
}
let outputSource
if (map) {
outputSource = new SourceMapSource(
code,
file,
JSON.parse(map),
input,
inputSourceMap
)
} else {
outputSource = new RawSource(code)
}
// Updating assets
processedAssets.add((compilation.assets[file] = outputSource))
// Handling warnings
if (warnings && warnings.length > 0) {
warnings.forEach(warning => {
const builtWarning = TerserPlugin.buildWarning(
warning,
file,
sourceMap,
new RequestShortener(compiler.context),
this.options.warningsFilter
)
if (builtWarning) {
compilation.warnings.push(builtWarning)
}
})
}
})
taskRunner.exit()
callback()
})
}
const plugin = { name: this.constructor.name }
compiler.hooks.compilation.tap(plugin, compilation => {
if (this.options.sourceMap) {
compilation.hooks.buildModule.tap(plugin, moduleArg => {
// to get detailed location info about errors
moduleArg.useSourceMap = true
})
}
const { mainTemplate, chunkTemplate } = compilation
// Regenerate `contenthash` for minified assets
for (const template of [mainTemplate, chunkTemplate]) {
template.hooks.hashForChunk.tap(plugin, hash => {
// Terser version
// Has to be updated when options change too
hash.update('3.17.0')
return hash
})
}
compilation.hooks.optimizeChunkAssets.tapAsync(
plugin,
optimizeFn.bind(this, compilation)
)
})
}
}
/* eslint-disable
arrow-body-style
*/
import { minify as terser, MinifyOptions } from 'next/dist/compiled/terser'
const IS_MODERN_OUTPUT = /\.module\.js$/
const buildTerserOptions = ({
ecma,
warnings,
parse = {},
compress = {},
mangle,
module,
output,
toplevel,
ie8,
/* eslint-disable camelcase */
keep_classnames,
keep_fnames,
/* eslint-enable camelcase */
safari10,
}: MinifyOptions = {}) => ({
ecma,
warnings,
parse: { ...parse },
compress: typeof compress === 'boolean' ? compress : { ...compress },
// eslint-disable-next-line no-nested-ternary
mangle:
mangle == null
? true
: typeof mangle === 'boolean'
? mangle
: { ...mangle },
output: {
shebang: true,
comments: false,
beautify: false,
semicolons: true,
...output,
},
module,
toplevel,
ie8,
keep_classnames,
keep_fnames,
safari10,
})
const minify = (options: {
file: string
input: string
inputSourceMap?: string
terserOptions?: MinifyOptions
}) => {
const { file, input, inputSourceMap } = options
// Copy terser options
const terserOptions = buildTerserOptions(options.terserOptions) as any
if (IS_MODERN_OUTPUT.test(file)) {
terserOptions.module = true
terserOptions.ecma = terserOptions.compress.ecma = terserOptions.output.ecma = 8
}
// Add source map data
if (inputSourceMap) {
terserOptions.sourceMap = {
content: inputSourceMap,
}
}
const { error, map, code, warnings } = terser(
{ [file]: input },
terserOptions
)
return { error, map, code, warnings }
}
export default minify
{
"additionalProperties": false,
"definitions": {
"file-conditions": {
"anyOf": [
{
"instanceof": "RegExp"
},
{
"type": "string"
}
]
}
},
"properties": {
"test": {
"anyOf": [
{
"$ref": "#/definitions/file-conditions"
},
{
"items": {
"anyOf": [
{
"$ref": "#/definitions/file-conditions"
}
]
},
"type": "array"
}
]
},
"include": {
"anyOf": [
{
"$ref": "#/definitions/file-conditions"
},
{
"items": {
"anyOf": [
{
"$ref": "#/definitions/file-conditions"
}
]
},
"type": "array"
}
]
},
"exclude": {
"anyOf": [
{
"$ref": "#/definitions/file-conditions"
},
{
"items": {
"anyOf": [
{
"$ref": "#/definitions/file-conditions"
}
]
},
"type": "array"
}
]
},
"chunkFilter": {
"instanceof": "Function"
},
"cache": {
"anyOf": [
{
"type": "boolean"
},
{
"type": "string"
}
]
},
"cacheKeys": {
"instanceof": "Function"
},
"parallel": {
"anyOf": [
{
"type": "boolean"
},
{
"type": "integer"
}
]
},
"sourceMap": {
"type": "boolean"
},
"minify": {
"instanceof": "Function"
},
"terserOptions": {
"additionalProperties": true,
"type": "object"
},
"extractComments": {
"anyOf": [
{
"type": "boolean"
},
{
"type": "string"
},
{
"instanceof": "RegExp"
},
{
"instanceof": "Function"
},
{
"additionalProperties": false,
"properties": {
"condition": {
"anyOf": [
{
"type": "boolean"
},
{
"type": "string"
},
{
"instanceof": "RegExp"
},
{
"instanceof": "Function"
}
]
},
"filename": {
"anyOf": [
{
"type": "string"
},
{
"instanceof": "Function"
}
]
},
"banner": {
"anyOf": [
{
"type": "boolean"
},
{
"type": "string"
},
{
"instanceof": "Function"
}
]
}
},
"type": "object"
}
]
},
"warningsFilter": {
"instanceof": "Function"
}
},
"type": "object"
}
This diff is collapsed.
{"name":"terser-webpack-plugin","main":"cjs.js","author":"webpack Contrib Team","license":"MIT"}
"use strict";
const {
minify: terserMinify
} = require('terser');
const buildTerserOptions = ({
ecma,
warnings,
parse = {},
compress = {},
mangle,
module,
output,
toplevel,
nameCache,
ie8,
/* eslint-disable camelcase */
keep_classnames,
keep_fnames,
/* eslint-enable camelcase */
safari10
} = {}) => ({
ecma,
warnings,
parse: { ...parse
},
compress: typeof compress === 'boolean' ? compress : { ...compress
},
// eslint-disable-next-line no-nested-ternary
mangle: mangle == null ? true : typeof mangle === 'boolean' ? mangle : { ...mangle
},
output: {
beautify: false,
...output
},
module,
// Ignoring sourceMap from options
sourceMap: null,
toplevel,
nameCache,
ie8,
keep_classnames,
keep_fnames,
safari10
});
function isObject(value) {
const type = typeof value;
return value != null && (type === 'object' || type === 'function');
}
const buildComments = (options, terserOptions, extractedComments) => {
const condition = {};
const commentsOpts = terserOptions.output.comments;
const {
extractComments
} = options;
condition.preserve = typeof commentsOpts !== 'undefined' ? commentsOpts : false;
if (typeof extractComments === 'boolean' && extractComments) {
condition.extract = 'some';
} else if (typeof extractComments === 'string' || extractComments instanceof RegExp) {
condition.extract = extractComments;
} else if (typeof extractComments === 'function') {
condition.extract = extractComments;
} else if (isObject(extractComments)) {
condition.extract = typeof extractComments.condition === 'boolean' && extractComments.condition ? 'some' : typeof extractComments.condition !== 'undefined' ? extractComments.condition : 'some';
} else {
// No extract
// Preserve using "commentsOpts" or "some"
condition.preserve = typeof commentsOpts !== 'undefined' ? commentsOpts : 'some';
condition.extract = false;
} // Ensure that both conditions are functions
['preserve', 'extract'].forEach(key => {
let regexStr;
let regex;
switch (typeof condition[key]) {
case 'boolean':
condition[key] = condition[key] ? () => true : () => false;
break;
case 'function':
break;
case 'string':
if (condition[key] === 'all') {
condition[key] = () => true;
break;
}
if (condition[key] === 'some') {
condition[key] = (astNode, comment) => {
return comment.type === 'comment2' && /@preserve|@lic|@cc_on|^\**!/i.test(comment.value);
};
break;
}
regexStr = condition[key];
condition[key] = (astNode, comment) => {
return new RegExp(regexStr).test(comment.value);
};
break;
default:
regex = condition[key];
condition[key] = (astNode, comment) => regex.test(comment.value);
}
}); // Redefine the comments function to extract and preserve
// comments according to the two conditions
return (astNode, comment) => {
if (condition.extract(astNode, comment)) {
const commentText = comment.type === 'comment2' ? `/*${comment.value}*/` : `//${comment.value}`; // Don't include duplicate comments
if (!extractedComments.includes(commentText)) {
extractedComments.push(commentText);
}
}
return condition.preserve(astNode, comment);
};
};
const minify = options => {
const {
file,
input,
inputSourceMap,
minify: minifyFn
} = options;
if (minifyFn) {
return minifyFn({
[file]: input
}, inputSourceMap);
} // Copy terser options
const terserOptions = buildTerserOptions(options.terserOptions); // Let terser generate a SourceMap
if (inputSourceMap) {
terserOptions.sourceMap = {
asObject: true
};
}
const extractedComments = [];
terserOptions.output.comments = buildComments(options, terserOptions, extractedComments);
const {
error,
map,
code,
warnings
} = terserMinify({
[file]: input
}, terserOptions);
return {
error,
map,
code,
warnings,
extractedComments
};
};
function transform(options) {
// 'use strict' => this === undefined (Clean Scope)
// Safer for possible security issues, albeit not critical at all here
// eslint-disable-next-line no-new-func, no-param-reassign
options = new Function('exports', 'require', 'module', '__filename', '__dirname', `'use strict'\nreturn ${options}`)(exports, require, module, __filename, __dirname);
const result = minify(options);
if (result.error) {
throw result.error;
} else {
return result;
}
}
module.exports.minify = minify;
module.exports.transform = transform;
\ No newline at end of file
This diff is collapsed.
...@@ -139,6 +139,7 @@ ...@@ -139,6 +139,7 @@
"@types/resolve": "0.0.8", "@types/resolve": "0.0.8",
"@types/send": "0.14.4", "@types/send": "0.14.4",
"@types/styled-jsx": "2.2.8", "@types/styled-jsx": "2.2.8",
"@types/terser-webpack-plugin": "2.2.0",
"@types/text-table": "0.2.1", "@types/text-table": "0.2.1",
"@types/webpack-dev-middleware": "2.0.3", "@types/webpack-dev-middleware": "2.0.3",
"@types/webpack-hot-middleware": "2.16.5", "@types/webpack-hot-middleware": "2.16.5",
...@@ -195,7 +196,8 @@ ...@@ -195,7 +196,8 @@
"string-hash": "1.1.3", "string-hash": "1.1.3",
"strip-ansi": "5.2.0", "strip-ansi": "5.2.0",
"taskr": "1.1.0", "taskr": "1.1.0",
"terser": "4.4.2", "terser": "4.6.11",
"terser-webpack-plugin": "gist:1b826e8b64f73158df99990d1b4624fa",
"text-table": "0.2.0", "text-table": "0.2.0",
"thread-loader": "2.1.3", "thread-loader": "2.1.3",
"typescript": "3.7.3", "typescript": "3.7.3",
......
...@@ -41,11 +41,15 @@ const externals = { ...@@ -41,11 +41,15 @@ const externals = {
// Webpack indirect and direct dependencies: // Webpack indirect and direct dependencies:
webpack: 'webpack', webpack: 'webpack',
'webpack-sources': 'webpack-sources',
// dependents: webpack-dev-middleware // dependents: webpack-dev-middleware
'webpack/lib/node/NodeOutputFileSystem': 'webpack/lib/node/NodeOutputFileSystem':
'webpack/lib/node/NodeOutputFileSystem', 'webpack/lib/node/NodeOutputFileSystem',
// dependents: terser-webpack-plugin
'webpack/lib/cache/getLazyHashedEtag': 'webpack/lib/cache/getLazyHashedEtag',
'webpack/lib/RequestShortener': 'webpack/lib/RequestShortener',
chokidar: 'chokidar', chokidar: 'chokidar',
// dependents: babel-loader, async-retry, autodll-webpack-plugin, cache-loader // dependents: babel-loader, async-retry, autodll-webpack-plugin, cache-loader, terser-webpack-plugin
'find-cache-dir': 'find-cache-dir', 'find-cache-dir': 'find-cache-dir',
// dependents: thread-loader // dependents: thread-loader
'loader-runner': 'loader-runner', 'loader-runner': 'loader-runner',
...@@ -57,6 +61,9 @@ const externals = { ...@@ -57,6 +61,9 @@ const externals = {
'neo-async': 'neo-async', 'neo-async': 'neo-async',
// dependents: cache-loader, style-loader, file-loader // dependents: cache-loader, style-loader, file-loader
'schema-utils': 'schema-utils', 'schema-utils': 'schema-utils',
// dependents: terser-webpack-plugin
'jest-worker': 'jest-worker',
cacache: 'cacache',
} }
// eslint-disable-next-line camelcase // eslint-disable-next-line camelcase
...@@ -492,6 +499,16 @@ export async function ncc_webpack_hot_middleware(task, opts) { ...@@ -492,6 +499,16 @@ export async function ncc_webpack_hot_middleware(task, opts) {
.ncc({ packageName: 'webpack-hot-middleware', externals }) .ncc({ packageName: 'webpack-hot-middleware', externals })
.target('compiled/webpack-hot-middleware') .target('compiled/webpack-hot-middleware')
} }
externals['terser-webpack-plugin'] = 'next/dist/compiled/terser-webpack-plugin'
export async function ncc_terser_webpack_plugin(task, opts) {
await task
.source(
opts.src || relative(__dirname, require.resolve('terser-webpack-plugin'))
)
.ncc({ packageName: 'terser-webpack-plugin', externals })
.target('compiled/terser-webpack-plugin')
}
externals['path-to-regexp'] = 'next/dist/compiled/path-to-regexp' externals['path-to-regexp'] = 'next/dist/compiled/path-to-regexp'
export async function path_to_regexp(task, opts) { export async function path_to_regexp(task, opts) {
await task await task
...@@ -578,6 +595,7 @@ export async function ncc(task) { ...@@ -578,6 +595,7 @@ export async function ncc(task) {
'ncc_unistore', 'ncc_unistore',
'ncc_webpack_dev_middleware', 'ncc_webpack_dev_middleware',
'ncc_webpack_hot_middleware', 'ncc_webpack_hot_middleware',
'ncc_terser_webpack_plugin',
]) ])
} }
......
...@@ -212,6 +212,10 @@ declare module 'next/dist/compiled/webpack-hot-middleware' { ...@@ -212,6 +212,10 @@ declare module 'next/dist/compiled/webpack-hot-middleware' {
import m from 'webpack-hot-middleware' import m from 'webpack-hot-middleware'
export = m export = m
} }
declare module 'next/dist/compiled/terser-webpack-plugin' {
import m from 'terser-webpack-plugin'
export = m
}
declare module 'autodll-webpack-plugin' { declare module 'autodll-webpack-plugin' {
import webpack from 'webpack' import webpack from 'webpack'
......
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