UNPKG

47.4 kBJavaScriptView Raw
1"use strict";exports.__esModule=true;exports.attachReactRefresh=attachReactRefresh;exports.default=getBaseWebpackConfig;var _ReactRefreshWebpackPlugin=_interopRequireDefault(require("@next/react-refresh-utils/ReactRefreshWebpackPlugin"));var _chalk=_interopRequireDefault(require("chalk"));var _crypto=_interopRequireDefault(require("crypto"));var _fs=require("fs");var _codeFrame=require("next/dist/compiled/babel/code-frame");var _semver=_interopRequireDefault(require("next/dist/compiled/semver"));var _webpack=require("next/dist/compiled/webpack/webpack");var _path=_interopRequireWildcard(require("path"));var _constants=require("../lib/constants");var _fileExists=require("../lib/file-exists");var _getPackageVersion=require("../lib/get-package-version");var _getTypeScriptConfiguration=require("../lib/typescript/getTypeScriptConfiguration");var _constants2=require("../next-server/lib/constants");var _utils=require("../next-server/lib/utils");var _findPageFile=require("../server/lib/find-page-file");var Log=_interopRequireWildcard(require("./output/log"));var _config=require("./webpack/config");var _overrideCssConfiguration=require("./webpack/config/blocks/css/overrideCssConfiguration");var _buildManifestPlugin=_interopRequireDefault(require("./webpack/plugins/build-manifest-plugin"));var _buildStatsPlugin=_interopRequireDefault(require("./webpack/plugins/build-stats-plugin"));var _chunkNamesPlugin=_interopRequireDefault(require("./webpack/plugins/chunk-names-plugin"));var _jsconfigPathsPlugin=require("./webpack/plugins/jsconfig-paths-plugin");var _nextDropClientPagePlugin=require("./webpack/plugins/next-drop-client-page-plugin");var _nextjsSsrImport=_interopRequireDefault(require("./webpack/plugins/nextjs-ssr-import"));var _nextjsSsrModuleCache=_interopRequireDefault(require("./webpack/plugins/nextjs-ssr-module-cache"));var _pagesManifestPlugin=_interopRequireDefault(require("./webpack/plugins/pages-manifest-plugin"));var _profilingPlugin=require("./webpack/plugins/profiling-plugin");var _reactLoadablePlugin=require("./webpack/plugins/react-loadable-plugin");var _serverlessPlugin=require("./webpack/plugins/serverless-plugin");var _webpackConformancePlugin=_interopRequireWildcard(require("./webpack/plugins/webpack-conformance-plugin"));var _wellknownErrorsPlugin=require("./webpack/plugins/wellknown-errors-plugin");var _css=require("./webpack/config/blocks/css");function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj};}function _getRequireWildcardCache(){if(typeof WeakMap!=="function")return null;var cache=new WeakMap();_getRequireWildcardCache=function(){return cache;};return cache;}function _interopRequireWildcard(obj){if(obj&&obj.__esModule){return obj;}if(obj===null||typeof obj!=="object"&&typeof obj!=="function"){return{default:obj};}var cache=_getRequireWildcardCache();if(cache&&cache.has(obj)){return cache.get(obj);}var newObj={};var hasPropertyDescriptor=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var key in obj){if(Object.prototype.hasOwnProperty.call(obj,key)){var desc=hasPropertyDescriptor?Object.getOwnPropertyDescriptor(obj,key):null;if(desc&&(desc.get||desc.set)){Object.defineProperty(newObj,key,desc);}else{newObj[key]=obj[key];}}}newObj.default=obj;if(cache){cache.set(obj,newObj);}return newObj;}const devtoolRevertWarning=(0,_utils.execOnce)(devtool=>{console.warn(_chalk.default.yellow.bold('Warning: ')+_chalk.default.bold(`Reverting webpack devtool to '${devtool}'.\n`)+'Changing the webpack devtool in development mode will cause severe performance regressions.\n'+'Read more: https://nextjs.org/docs/messages/improper-devtool');});function parseJsonFile(filePath){const JSON5=require('next/dist/compiled/json5');const contents=(0,_fs.readFileSync)(filePath,'utf8');// Special case an empty file
2if(contents.trim()===''){return{};}try{return JSON5.parse(contents);}catch(err){const codeFrame=(0,_codeFrame.codeFrameColumns)(String(contents),{start:{line:err.lineNumber,column:err.columnNumber}},{message:err.message,highlightCode:true});throw new Error(`Failed to parse "${filePath}":\n${codeFrame}`);}}function getOptimizedAliases(isServer){if(isServer){return{};}const stubWindowFetch=_path.default.join(__dirname,'polyfills','fetch','index.js');const stubObjectAssign=_path.default.join(__dirname,'polyfills','object-assign.js');const shimAssign=_path.default.join(__dirname,'polyfills','object.assign');return Object.assign({},{unfetch$:stubWindowFetch,'isomorphic-unfetch$':stubWindowFetch,'whatwg-fetch$':_path.default.join(__dirname,'polyfills','fetch','whatwg-fetch.js')},{'object-assign$':stubObjectAssign,// Stub Package: object.assign
3'object.assign/auto':_path.default.join(shimAssign,'auto.js'),'object.assign/implementation':_path.default.join(shimAssign,'implementation.js'),'object.assign$':_path.default.join(shimAssign,'index.js'),'object.assign/polyfill':_path.default.join(shimAssign,'polyfill.js'),'object.assign/shim':_path.default.join(shimAssign,'shim.js'),// Replace: full URL polyfill with platform-based polyfill
4url:require.resolve('native-url')});}function attachReactRefresh(webpackConfig,targetLoader){var _webpackConfig$module;let injections=0;const reactRefreshLoaderName='@next/react-refresh-utils/loader';const reactRefreshLoader=require.resolve(reactRefreshLoaderName);(_webpackConfig$module=webpackConfig.module)==null?void 0:_webpackConfig$module.rules.forEach(rule=>{const curr=rule.use;// When the user has configured `defaultLoaders.babel` for a input file:
5if(curr===targetLoader){++injections;rule.use=[reactRefreshLoader,curr];}else if(Array.isArray(curr)&&curr.some(r=>r===targetLoader)&&// Check if loader already exists:
6!curr.some(r=>r===reactRefreshLoader||r===reactRefreshLoaderName)){++injections;const idx=curr.findIndex(r=>r===targetLoader);// Clone to not mutate user input
7rule.use=[...curr];// inject / input: [other, babel] output: [other, refresh, babel]:
8rule.use.splice(idx,0,reactRefreshLoader);}});if(injections){Log.info(`automatically enabled Fast Refresh for ${injections} custom loader${injections>1?'s':''}`);}}const WEBPACK_RESOLVE_OPTIONS={// This always uses commonjs resolving, assuming API is identical
9// between ESM and CJS in a package
10// Otherwise combined ESM+CJS packages will never be external
11// as resolving mismatch would lead to opt-out from being external.
12dependencyType:'commonjs',symlinks:true};const NODE_RESOLVE_OPTIONS={dependencyType:'commonjs',modules:['node_modules'],alias:false,fallback:false,exportsFields:['exports'],importsFields:['imports'],conditionNames:['node','require','module'],descriptionFiles:['package.json'],extensions:['.js','.json','.node'],enforceExtensions:false,symlinks:true,mainFields:['main'],mainFiles:['index'],roots:[],fullySpecified:false,preferRelative:false,preferAbsolute:false,restrictions:[]};async function getBaseWebpackConfig(dir,{buildId,config,dev=false,isServer=false,pagesDir,target='server',reactProductionProfiling=false,entrypoints,rewrites,isDevFallback=false}){var _semver$coerce,_jsConfig,_jsConfig$compilerOpt,_config$conformance,_config$conformance$D,_config$i18n,_jsConfig2,_jsConfig2$compilerOp,_webpackConfig$module2,_webpackConfig$module3,_webpackConfig$module4;const hasRewrites=rewrites.beforeFiles.length>0||rewrites.afterFiles.length>0||rewrites.fallback.length>0;const hasReactRefresh=dev&&!isServer;const reactDomVersion=await(0,_getPackageVersion.getPackageVersion)({cwd:dir,name:'react-dom'});const hasReact18=Boolean(reactDomVersion)&&(_semver.default.gte(reactDomVersion,'18.0.0')||((_semver$coerce=_semver.default.coerce(reactDomVersion))==null?void 0:_semver$coerce.version)==='18.0.0');const hasReactPrerelease=Boolean(reactDomVersion)&&_semver.default.prerelease(reactDomVersion)!=null;const hasReactRoot=config.experimental.reactRoot||hasReact18;// Only inform during one of the builds
13if(!isServer){if(hasReactRoot){Log.info('Using the createRoot API for React');}if(hasReactPrerelease){Log.warn(`You are using an unsupported prerelease of 'react-dom' which may cause `+`unexpected or broken application behavior. Continue at your own risk.`);}}const babelConfigFile=await['.babelrc','.babelrc.json','.babelrc.js','.babelrc.mjs','.babelrc.cjs','babel.config.js','babel.config.json','babel.config.mjs','babel.config.cjs'].reduce(async(memo,filename)=>{const configFilePath=_path.default.join(dir,filename);return(await memo)||((await(0,_fileExists.fileExists)(configFilePath))?configFilePath:undefined);},Promise.resolve(undefined));const distDir=_path.default.join(dir,config.distDir);// Webpack 5 can use the faster babel loader, webpack 5 has built-in caching for loaders
14// For webpack 4 the old loader is used as it has external caching
15const babelLoader=_webpack.isWebpack5?require.resolve('./babel/loader/index'):'next-babel-loader';const defaultLoaders={babel:{loader:babelLoader,options:{configFile:babelConfigFile,isServer,distDir,pagesDir,cwd:dir,// Webpack 5 has a built-in loader cache
16cache:!_webpack.isWebpack5,development:dev,hasReactRefresh,hasJsxRuntime:true}},// Backwards compat
17hotSelfAccept:{loader:'noop-loader'}};const babelIncludeRegexes=[/next[\\/]dist[\\/]next-server[\\/]lib/,/next[\\/]dist[\\/]client/,/next[\\/]dist[\\/]pages/,/[\\/](strip-ansi|ansi-regex)[\\/]/];// Support for NODE_PATH
18const nodePathList=(process.env.NODE_PATH||'').split(process.platform==='win32'?';':':').filter(p=>!!p);const isServerless=target==='serverless';const isServerlessTrace=target==='experimental-serverless-trace';// Intentionally not using isTargetLikeServerless helper
19const isLikeServerless=isServerless||isServerlessTrace;const outputDir=isLikeServerless?_constants2.SERVERLESS_DIRECTORY:_constants2.SERVER_DIRECTORY;const outputPath=_path.default.join(distDir,isServer?outputDir:'');const totalPages=Object.keys(entrypoints).length;const clientEntries=!isServer?{// Backwards compatibility
20'main.js':[],...(dev?{[_constants2.CLIENT_STATIC_FILES_RUNTIME_REACT_REFRESH]:require.resolve(`@next/react-refresh-utils/runtime`),[_constants2.CLIENT_STATIC_FILES_RUNTIME_AMP]:`./`+(0,_path.relative)(dir,(0,_path.join)(_constants.NEXT_PROJECT_ROOT_DIST_CLIENT,'dev','amp-dev')).replace(/\\/g,'/')}:{}),[_constants2.CLIENT_STATIC_FILES_RUNTIME_MAIN]:`./`+_path.default.relative(dir,_path.default.join(_constants.NEXT_PROJECT_ROOT_DIST_CLIENT,dev?`next-dev.js`:'next.js')).replace(/\\/g,'/'),[_constants2.CLIENT_STATIC_FILES_RUNTIME_POLYFILLS]:_path.default.join(_constants.NEXT_PROJECT_ROOT_DIST_CLIENT,'polyfills.js')}:undefined;let typeScriptPath;try{typeScriptPath=require.resolve('typescript',{paths:[dir]});}catch(_){}const tsConfigPath=_path.default.join(dir,'tsconfig.json');const useTypeScript=Boolean(typeScriptPath&&(await(0,_fileExists.fileExists)(tsConfigPath)));let jsConfig;// jsconfig is a subset of tsconfig
21if(useTypeScript){const ts=await Promise.resolve(`${typeScriptPath}`).then(s=>_interopRequireWildcard(require(s)));const tsConfig=await(0,_getTypeScriptConfiguration.getTypeScriptConfiguration)(ts,tsConfigPath,true);jsConfig={compilerOptions:tsConfig.options};}const jsConfigPath=_path.default.join(dir,'jsconfig.json');if(!useTypeScript&&(await(0,_fileExists.fileExists)(jsConfigPath))){jsConfig=parseJsonFile(jsConfigPath);}let resolvedBaseUrl;if((_jsConfig=jsConfig)!=null&&(_jsConfig$compilerOpt=_jsConfig.compilerOptions)!=null&&_jsConfig$compilerOpt.baseUrl){resolvedBaseUrl=_path.default.resolve(dir,jsConfig.compilerOptions.baseUrl);}function getReactProfilingInProduction(){if(reactProductionProfiling){return{'react-dom$':'react-dom/profiling','scheduler/tracing':'scheduler/tracing-profiling'};}}const clientResolveRewrites=require.resolve('../next-server/lib/router/utils/resolve-rewrites');const clientResolveRewritesNoop=require.resolve('../next-server/lib/router/utils/resolve-rewrites-noop');const resolveConfig={// Disable .mjs for node_modules bundling
22extensions:isServer?['.js','.mjs',...(useTypeScript?['.tsx','.ts']:[]),'.jsx','.json','.wasm']:['.mjs','.js',...(useTypeScript?['.tsx','.ts']:[]),'.jsx','.json','.wasm'],modules:['node_modules',...nodePathList// Support for NODE_PATH environment variable
23],alias:{next:_constants.NEXT_PROJECT_ROOT,[_constants.PAGES_DIR_ALIAS]:pagesDir,[_constants.DOT_NEXT_ALIAS]:distDir,...getOptimizedAliases(isServer),...getReactProfilingInProduction(),[clientResolveRewrites]:hasRewrites?clientResolveRewrites:// With webpack 5 an alias can be pointed to false to noop
24_webpack.isWebpack5?false:clientResolveRewritesNoop},...(_webpack.isWebpack5&&!isServer?{// Full list of old polyfills is accessible here:
25// https://github.com/webpack/webpack/blob/2a0536cf510768111a3a6dceeb14cb79b9f59273/lib/ModuleNotFoundError.js#L13-L42
26fallback:{assert:require.resolve('assert/'),buffer:require.resolve('buffer/'),constants:require.resolve('constants-browserify'),crypto:require.resolve('crypto-browserify'),domain:require.resolve('domain-browser'),http:require.resolve('stream-http'),https:require.resolve('https-browserify'),os:require.resolve('os-browserify/browser'),path:require.resolve('path-browserify'),punycode:require.resolve('punycode'),process:require.resolve('process/browser'),// Handled in separate alias
27querystring:require.resolve('querystring-es3'),stream:require.resolve('stream-browserify'),string_decoder:require.resolve('string_decoder'),sys:require.resolve('util/'),timers:require.resolve('timers-browserify'),tty:require.resolve('tty-browserify'),// Handled in separate alias
28// url: require.resolve('url/'),
29util:require.resolve('util/'),vm:require.resolve('vm-browserify'),zlib:require.resolve('browserify-zlib')}}:undefined),mainFields:isServer?['main','module']:['browser','module','main'],plugins:_webpack.isWebpack5?// webpack 5+ has the PnP resolver built-in by default:
30[]:[require('pnp-webpack-plugin')]};const terserOptions={parse:{ecma:8},compress:{ecma:5,warnings:false,// The following two options are known to break valid JavaScript code
31comparisons:false,inline:2// https://github.com/vercel/next.js/issues/7178#issuecomment-493048965
32},mangle:{safari10:true},output:{ecma:5,safari10:true,comments:false,// Fixes usage of Emoji and certain Regex
33ascii_only:true}};const isModuleCSS=module=>{return(// mini-css-extract-plugin
34module.type===`css/mini-extract`||// extract-css-chunks-webpack-plugin (old)
35module.type===`css/extract-chunks`||// extract-css-chunks-webpack-plugin (new)
36module.type===`css/extract-css-chunks`);};// Contains various versions of the Webpack SplitChunksPlugin used in different build types
37const splitChunksConfigs={dev:{cacheGroups:{default:false,vendors:false}},prodGranular:{// Keep main and _app chunks unsplitted in webpack 5
38// as we don't need a separate vendor chunk from that
39// and all other chunk depend on them so there is no
40// duplication that need to be pulled out.
41chunks:_webpack.isWebpack5?chunk=>!/^(polyfills|main|pages\/_app)$/.test(chunk.name):'all',cacheGroups:{framework:{chunks:'all',name:'framework',// This regex ignores nested copies of framework libraries so they're
42// bundled with their issuer.
43// https://github.com/vercel/next.js/pull/9012
44test:/(?<!node_modules.*)[\\/]node_modules[\\/](react|react-dom|scheduler|prop-types|use-subscription)[\\/]/,priority:40,// Don't let webpack eliminate this chunk (prevents this chunk from
45// becoming a part of the commons chunk)
46enforce:true},lib:{test(module){return module.size()>160000&&/node_modules[/\\]/.test(module.nameForCondition()||'');},name(module){const hash=_crypto.default.createHash('sha1');if(isModuleCSS(module)){module.updateHash(hash);}else{if(!module.libIdent){throw new Error(`Encountered unknown module type: ${module.type}. Please open an issue.`);}hash.update(module.libIdent({context:dir}));}return hash.digest('hex').substring(0,8);},priority:30,minChunks:1,reuseExistingChunk:true},commons:{name:'commons',minChunks:totalPages,priority:20},...(_webpack.isWebpack5?undefined:{default:false,vendors:false,shared:{name(module,chunks){return _crypto.default.createHash('sha1').update(chunks.reduce((acc,chunk)=>{return acc+chunk.name;},'')).digest('hex')+(isModuleCSS(module)?'_CSS':'');},priority:10,minChunks:2,reuseExistingChunk:true}})},maxInitialRequests:25,minSize:20000}};// Select appropriate SplitChunksPlugin config for this build
47let splitChunksConfig;if(dev){splitChunksConfig=_webpack.isWebpack5?false:splitChunksConfigs.dev;}else{splitChunksConfig=splitChunksConfigs.prodGranular;}const crossOrigin=config.crossOrigin;let customAppFile=await(0,_findPageFile.findPageFile)(pagesDir,'/_app',config.pageExtensions);if(customAppFile){customAppFile=_path.default.resolve(_path.default.join(pagesDir,customAppFile));}const conformanceConfig=Object.assign({ReactSyncScriptsConformanceCheck:{enabled:true},MinificationConformanceCheck:{enabled:true},DuplicatePolyfillsConformanceCheck:{enabled:true,BlockedAPIToBePolyfilled:Object.assign([],['fetch'],((_config$conformance=config.conformance)==null?void 0:(_config$conformance$D=_config$conformance.DuplicatePolyfillsConformanceCheck)==null?void 0:_config$conformance$D.BlockedAPIToBePolyfilled)||[])},GranularChunksConformanceCheck:{enabled:true}},config.conformance);async function handleExternals(context,request,getResolve){// We need to externalize internal requests for files intended to
48// not be bundled.
49const isLocal=request.startsWith('.')||// Always check for unix-style path, as webpack sometimes
50// normalizes as posix.
51_path.default.posix.isAbsolute(request)||// When on Windows, we also want to check for Windows-specific
52// absolute paths.
53process.platform==='win32'&&_path.default.win32.isAbsolute(request);// Relative requires don't need custom resolution, because they
54// are relative to requests we've already resolved here.
55// Absolute requires (require('/foo')) are extremely uncommon, but
56// also have no need for customization as they're already resolved.
57if(isLocal){if(!/[/\\]next-server[/\\]/.test(request)){return;}}else{if(/^(?:next$|react(?:$|\/))/.test(request)){return`commonjs ${request}`;}const notExternalModules=/^(?:private-next-pages\/|next\/(?:dist\/pages\/|(?:app|document|link|image|constants)$)|string-hash$)/;if(notExternalModules.test(request)){return;}}const resolve=getResolve(WEBPACK_RESOLVE_OPTIONS);// Resolve the import with the webpack provided context, this
58// ensures we're resolving the correct version when multiple
59// exist.
60let res;try{res=await resolve(context,request);}catch(err){// If the request cannot be resolved, we need to tell webpack to
61// "bundle" it so that webpack shows an error (that it cannot be
62// resolved).
63return;}// Same as above, if the request cannot be resolved we need to have
64// webpack "bundle" it so it surfaces the not found error.
65if(!res){return;}if(isLocal){// we need to process next-server/lib/router/router so that
66// the DefinePlugin can inject process.env values
67const isNextExternal=/next[/\\]dist[/\\]next-server[/\\](?!lib[/\\]router[/\\]router)/.test(res);if(isNextExternal){// Generate Next.js external import
68const externalRequest=_path.default.posix.join('next','dist',_path.default.relative(// Root of Next.js package:
69_path.default.join(__dirname,'..'),res)// Windows path normalization
70.replace(/\\/g,'/'));return`commonjs ${externalRequest}`;}else{return;}}// Bundled Node.js code is relocated without its node_modules tree.
71// This means we need to make sure its request resolves to the same
72// package that'll be available at runtime. If it's not identical,
73// we need to bundle the code (even if it _should_ be external).
74let baseRes;try{const baseResolve=getResolve(NODE_RESOLVE_OPTIONS);baseRes=await baseResolve(dir,request);}catch(err){baseRes=null;}// Same as above: if the package, when required from the root,
75// would be different from what the real resolution would use, we
76// cannot externalize it.
77// if res or baseRes are symlinks they could point to the the same file,
78// but the resolver will resolve symlinks so this is already handled
79if(baseRes!==res){return;}if(res.match(/next[/\\]dist[/\\]next-server[/\\](?!lib[/\\]router[/\\]router)/)){return`commonjs ${request}`;}// Default pages have to be transpiled
80if(res.match(/[/\\]next[/\\]dist[/\\]/)||// This is the @babel/plugin-transform-runtime "helpers: true" option
81res.match(/node_modules[/\\]@babel[/\\]runtime[/\\]/)){return;}// Webpack itself has to be compiled because it doesn't always use module relative paths
82if(res.match(/node_modules[/\\]webpack/)||res.match(/node_modules[/\\]css-loader/)){return;}// Anything else that is standard JavaScript within `node_modules`
83// can be externalized.
84if(/node_modules[/\\].*\.c?js$/.test(res)){return`commonjs ${request}`;}// Default behavior: bundle the code!
85}const emacsLockfilePattern='**/.#*';let webpackConfig={externals:!isServer?// make sure importing "next" is handled gracefully for client
86// bundles in case a user imported types and it wasn't removed
87// TODO: should we warn/error for this instead?
88['next']:!isServerless?[_webpack.isWebpack5?({context,request,getResolve})=>handleExternals(context,request,getResolve):(context,request,callback)=>handleExternals(context,request,()=>(resolveContext,requestToResolve)=>new Promise(resolve=>resolve(require.resolve(requestToResolve,{paths:[resolveContext]})))).then(result=>callback(undefined,result),callback)]:[// When the 'serverless' target is used all node_modules will be compiled into the output bundles
89// So that the 'serverless' bundles have 0 runtime dependencies
90'next/dist/compiled/@ampproject/toolbox-optimizer',// except this one
91// Mark this as external if not enabled so it doesn't cause a
92// webpack error from being missing
93...(config.experimental.optimizeCss?[]:['critters'])],optimization:{// Webpack 5 uses a new property for the same functionality
94...(_webpack.isWebpack5?{emitOnErrors:!dev}:{noEmitOnErrors:dev}),checkWasmTypes:false,nodeEnv:false,splitChunks:isServer?_webpack.isWebpack5&&!dev?{filename:'[name].js',// allow to split entrypoints
95chunks:'all',// size of files is not so relevant for server build
96// we want to prefer deduplication to load less code
97minSize:1000}:false:splitChunksConfig,runtimeChunk:isServer?_webpack.isWebpack5&&!isLikeServerless?{name:'webpack-runtime'}:undefined:{name:_constants2.CLIENT_STATIC_FILES_RUNTIME_WEBPACK},minimize:!(dev||isServer),minimizer:[// Minify JavaScript
98compiler=>{// @ts-ignore No typings yet
99const{TerserPlugin}=require('./webpack/plugins/terser-webpack-plugin/src/index.js');new TerserPlugin({cacheDir:_path.default.join(distDir,'cache','next-minifier'),parallel:config.experimental.cpus,terserOptions}).apply(compiler);},// Minify CSS
100compiler=>{const{CssMinimizerPlugin}=require('./webpack/plugins/css-minimizer-plugin');new CssMinimizerPlugin({postcssOptions:{map:{// `inline: false` generates the source map in a separate file.
101// Otherwise, the CSS file is needlessly large.
102inline:false,// `annotation: false` skips appending the `sourceMappingURL`
103// to the end of the CSS file. Webpack already handles this.
104annotation:false}}}).apply(compiler);}]},context:dir,node:{setImmediate:false},// Kept as function to be backwards compatible
105// @ts-ignore TODO webpack 5 typings needed
106entry:async()=>{return{...(clientEntries?clientEntries:{}),...entrypoints};},watchOptions:{aggregateTimeout:5,ignored:['**/.git/**','**/node_modules/**','**/.next/**',// can be removed after https://github.com/paulmillr/chokidar/issues/955 is released
107emacsLockfilePattern]},output:{...(_webpack.isWebpack5?{environment:{arrowFunction:false,bigIntLiteral:false,const:false,destructuring:false,dynamicImport:false,forOf:false,module:false}}:{}),// we must set publicPath to an empty value to override the default of
108// auto which doesn't work in IE11
109publicPath:`${config.assetPrefix||''}/_next/`,path:isServer&&_webpack.isWebpack5&&!dev?_path.default.join(outputPath,'chunks'):outputPath,// On the server we don't use hashes
110filename:isServer?_webpack.isWebpack5&&!dev?'../[name].js':'[name].js':`static/chunks/${isDevFallback?'fallback/':''}[name]${dev?'':_webpack.isWebpack5?'-[contenthash]':'-[chunkhash]'}.js`,library:isServer?undefined:'_N_E',libraryTarget:isServer?'commonjs2':'assign',hotUpdateChunkFilename:_webpack.isWebpack5?'static/webpack/[id].[fullhash].hot-update.js':'static/webpack/[id].[hash].hot-update.js',hotUpdateMainFilename:_webpack.isWebpack5?'static/webpack/[fullhash].[runtime].hot-update.json':'static/webpack/[hash].hot-update.json',// This saves chunks with the name given via `import()`
111chunkFilename:isServer?'[name].js':`static/chunks/${isDevFallback?'fallback/':''}${dev?'[name]':'[name].[contenthash]'}.js`,strictModuleExceptionHandling:true,crossOriginLoading:crossOrigin,futureEmitAssets:!dev,webassemblyModuleFilename:'static/wasm/[modulehash].wasm'},performance:false,resolve:resolveConfig,resolveLoader:{// The loaders Next.js provides
112alias:['emit-file-loader','error-loader','next-babel-loader','next-client-pages-loader','next-image-loader','next-serverless-loader','noop-loader','next-style-loader'].reduce((alias,loader)=>{// using multiple aliases to replace `resolveLoader.modules`
113alias[loader]=_path.default.join(__dirname,'webpack','loaders',loader);return alias;},{}),modules:['node_modules',...nodePathList// Support for NODE_PATH environment variable
114],plugins:_webpack.isWebpack5?[]:[require('pnp-webpack-plugin')]},module:{rules:[...(_webpack.isWebpack5?[// TODO: FIXME: do NOT webpack 5 support with this
115// x-ref: https://github.com/webpack/webpack/issues/11467
116{test:/\.m?js/,resolve:{fullySpecified:false}}]:[]),{test:/\.(tsx|ts|js|mjs|jsx)$/,...(config.experimental.externalDir?// Allowing importing TS/TSX files from outside of the root dir.
117{}:{include:[dir,...babelIncludeRegexes]}),exclude:excludePath=>{if(babelIncludeRegexes.some(r=>r.test(excludePath))){return false;}return /node_modules/.test(excludePath);},use:hasReactRefresh?[require.resolve('@next/react-refresh-utils/loader'),defaultLoaders.babel]:defaultLoaders.babel}].filter(Boolean)},plugins:[hasReactRefresh&&new _ReactRefreshWebpackPlugin.default(_webpack.webpack),// Makes sure `Buffer` and `process` are polyfilled in client-side bundles (same behavior as webpack 4)
118_webpack.isWebpack5&&!isServer&&new _webpack.webpack.ProvidePlugin({Buffer:[require.resolve('buffer'),'Buffer'],process:[require.resolve('process')]}),// This plugin makes sure `output.filename` is used for entry chunks
119!_webpack.isWebpack5&&new _chunkNamesPlugin.default(),new _webpack.webpack.DefinePlugin({...Object.keys(process.env).reduce((prev,key)=>{if(key.startsWith('NEXT_PUBLIC_')){prev[`process.env.${key}`]=JSON.stringify(process.env[key]);}return prev;},{}),...Object.keys(config.env).reduce((acc,key)=>{if(/^(?:NODE_.+)|^(?:__.+)$/i.test(key)){throw new Error(`The key "${key}" under "env" in next.config.js is not allowed. https://nextjs.org/docs/messages/env-key-not-allowed`);}return{...acc,[`process.env.${key}`]:JSON.stringify(config.env[key])};},{}),// TODO: enforce `NODE_ENV` on `process.env`, and add a test:
120'process.env.NODE_ENV':JSON.stringify(dev?'development':'production'),'process.env.__NEXT_CROSS_ORIGIN':JSON.stringify(crossOrigin),'process.browser':JSON.stringify(!isServer),'process.env.__NEXT_TEST_MODE':JSON.stringify(process.env.__NEXT_TEST_MODE),// This is used in client/dev-error-overlay/hot-dev-client.js to replace the dist directory
121...(dev&&!isServer?{'process.env.__NEXT_DIST_DIR':JSON.stringify(distDir)}:{}),'process.env.__NEXT_TRAILING_SLASH':JSON.stringify(config.trailingSlash),'process.env.__NEXT_BUILD_INDICATOR':JSON.stringify(config.devIndicators.buildActivity),'process.env.__NEXT_PLUGINS':JSON.stringify(config.experimental.plugins),'process.env.__NEXT_STRICT_MODE':JSON.stringify(config.reactStrictMode),'process.env.__NEXT_REACT_ROOT':JSON.stringify(hasReactRoot),'process.env.__NEXT_OPTIMIZE_FONTS':JSON.stringify(config.optimizeFonts&&!dev),'process.env.__NEXT_OPTIMIZE_IMAGES':JSON.stringify(config.experimental.optimizeImages),'process.env.__NEXT_OPTIMIZE_CSS':JSON.stringify(config.experimental.optimizeCss&&!dev),'process.env.__NEXT_SCROLL_RESTORATION':JSON.stringify(config.experimental.scrollRestoration),'process.env.__NEXT_IMAGE_OPTS':JSON.stringify({deviceSizes:config.images.deviceSizes,imageSizes:config.images.imageSizes,path:config.images.path,loader:config.images.loader,...(dev?{// pass domains in development to allow validating on the client
122domains:config.images.domains}:{})}),'process.env.__NEXT_ROUTER_BASEPATH':JSON.stringify(config.basePath),'process.env.__NEXT_HAS_REWRITES':JSON.stringify(hasRewrites),'process.env.__NEXT_I18N_SUPPORT':JSON.stringify(!!config.i18n),'process.env.__NEXT_I18N_DOMAINS':JSON.stringify((_config$i18n=config.i18n)==null?void 0:_config$i18n.domains),'process.env.__NEXT_ANALYTICS_ID':JSON.stringify(config.analyticsId),...(isServer?{// Fix bad-actors in the npm ecosystem (e.g. `node-formidable`)
123// This is typically found in unmaintained modules from the
124// pre-webpack era (common in server-side code)
125'global.GENTLY':JSON.stringify(false)}:undefined),// stub process.env with proxy to warn a missing value is
126// being accessed in development mode
127...(config.experimental.pageEnv&&dev?{'process.env':`
128 new Proxy(${isServer?'process.env':'{}'}, {
129 get(target, prop) {
130 if (typeof target[prop] === 'undefined') {
131 console.warn(\`An environment variable (\${prop}) that was not provided in the environment was accessed.\nSee more info here: https://nextjs.org/docs/messages/missing-env-value\`)
132 }
133 return target[prop]
134 }
135 })
136 `}:{})}),!isServer&&new _reactLoadablePlugin.ReactLoadablePlugin({filename:_constants2.REACT_LOADABLE_MANIFEST,pagesDir}),!isServer&&new _nextDropClientPagePlugin.DropClientPage(),// Moment.js is an extremely popular library that bundles large locale files
137// by default due to how Webpack interprets its code. This is a practical
138// solution that requires the user to opt into importing specific locales.
139// https://github.com/jmblog/how-to-optimize-momentjs-with-webpack
140config.excludeDefaultMomentLocales&&new _webpack.webpack.IgnorePlugin({resourceRegExp:/^\.\/locale$/,contextRegExp:/moment$/}),...(dev?(()=>{// Even though require.cache is server only we have to clear assets from both compilations
141// This is because the client compilation generates the build manifest that's used on the server side
142const{NextJsRequireCacheHotReloader}=require('./webpack/plugins/nextjs-require-cache-hot-reloader');const devPlugins=[new NextJsRequireCacheHotReloader()];if(!isServer){devPlugins.push(new _webpack.webpack.HotModuleReplacementPlugin());}return devPlugins;})():[]),// Webpack 5 no longer requires this plugin in production:
143!_webpack.isWebpack5&&!dev&&new _webpack.webpack.HashedModuleIdsPlugin(),!dev&&new _webpack.webpack.IgnorePlugin({resourceRegExp:/react-is/,contextRegExp:/(next-server|next)[\\/]dist[\\/]/}),isServerless&&isServer&&new _serverlessPlugin.ServerlessPlugin(),isServer&&new _pagesManifestPlugin.default({serverless:isLikeServerless,dev}),!_webpack.isWebpack5&&target==='server'&&isServer&&new _nextjsSsrModuleCache.default({outputPath}),isServer&&new _nextjsSsrImport.default(),!isServer&&new _buildManifestPlugin.default({buildId,rewrites,isDevFallback}),!dev&&!isServer&&config.experimental.stats&&new _buildStatsPlugin.default({distDir}),new _profilingPlugin.ProfilingPlugin(),config.optimizeFonts&&!dev&&isServer&&function(){const{FontStylesheetGatheringPlugin}=require('./webpack/plugins/font-stylesheet-gathering-plugin');return new FontStylesheetGatheringPlugin({isLikeServerless});}(),config.experimental.conformance&&!_webpack.isWebpack5&&!dev&&new _webpackConformancePlugin.default({tests:[!isServer&&conformanceConfig.MinificationConformanceCheck.enabled&&new _webpackConformancePlugin.MinificationConformanceCheck(),conformanceConfig.ReactSyncScriptsConformanceCheck.enabled&&new _webpackConformancePlugin.ReactSyncScriptsConformanceCheck({AllowedSources:conformanceConfig.ReactSyncScriptsConformanceCheck.allowedSources||[]}),!isServer&&conformanceConfig.DuplicatePolyfillsConformanceCheck.enabled&&new _webpackConformancePlugin.DuplicatePolyfillsConformanceCheck({BlockedAPIToBePolyfilled:conformanceConfig.DuplicatePolyfillsConformanceCheck.BlockedAPIToBePolyfilled}),!isServer&&conformanceConfig.GranularChunksConformanceCheck.enabled&&new _webpackConformancePlugin.GranularChunksConformanceCheck(splitChunksConfigs.prodGranular)].filter(Boolean)}),new _wellknownErrorsPlugin.WellKnownErrorsPlugin()].filter(Boolean)};// Support tsconfig and jsconfig baseUrl
144if(resolvedBaseUrl){var _webpackConfig$resolv,_webpackConfig$resolv2;(_webpackConfig$resolv=webpackConfig.resolve)==null?void 0:(_webpackConfig$resolv2=_webpackConfig$resolv.modules)==null?void 0:_webpackConfig$resolv2.push(resolvedBaseUrl);}if((_jsConfig2=jsConfig)!=null&&(_jsConfig2$compilerOp=_jsConfig2.compilerOptions)!=null&&_jsConfig2$compilerOp.paths&&resolvedBaseUrl){var _webpackConfig$resolv3,_webpackConfig$resolv4;(_webpackConfig$resolv3=webpackConfig.resolve)==null?void 0:(_webpackConfig$resolv4=_webpackConfig$resolv3.plugins)==null?void 0:_webpackConfig$resolv4.unshift(new _jsconfigPathsPlugin.JsConfigPathsPlugin(jsConfig.compilerOptions.paths,resolvedBaseUrl));}if(_webpack.isWebpack5){var _webpackConfig$output;// futureEmitAssets is on by default in webpack 5
145(_webpackConfig$output=webpackConfig.output)==null?true:delete _webpackConfig$output.futureEmitAssets;if(isServer&&dev){// Enable building of client compilation before server compilation in development
146// @ts-ignore dependencies exists
147webpackConfig.dependencies=['client'];}// webpack 5 no longer polyfills Node.js modules:
148if(webpackConfig.node)delete webpackConfig.node.setImmediate;// Due to bundling of webpack the default values can't be correctly detected
149// This restores the webpack defaults
150// @ts-ignore webpack 5
151webpackConfig.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
152webpackConfig.snapshot.managedPaths=[_path.default.resolve(match[1],'unplugged')];}}else{const match=/^(.+?[\\/]node_modules)[\\/]/.exec(require.resolve('jest-worker'));if(match){// @ts-ignore webpack 5
153webpackConfig.snapshot.managedPaths=[match[1]];}}if(process.versions.pnp==='1'){const match=/^(.+?[\\/]v4)[\\/]npm-jest-worker-[^\\/]+-[\da-f]{40}[\\/]node_modules[\\/]/.exec(require.resolve('jest-worker'));if(match){// @ts-ignore webpack 5
154webpackConfig.snapshot.immutablePaths=[match[1]];}}else if(process.versions.pnp==='3'){const match=/^(.+?)[\\/]jest-worker-npm-[^\\/]+\.zip[\\/]node_modules[\\/]/.exec(require.resolve('jest-worker'));if(match){// @ts-ignore webpack 5
155webpackConfig.snapshot.immutablePaths=[match[1]];}}if(dev){if(!webpackConfig.optimization){webpackConfig.optimization={};}webpackConfig.optimization.providedExports=false;webpackConfig.optimization.usedExports=false;}const configVars=JSON.stringify({crossOrigin:config.crossOrigin,pageExtensions:config.pageExtensions,trailingSlash:config.trailingSlash,buildActivity:config.devIndicators.buildActivity,plugins:config.experimental.plugins,reactStrictMode:config.reactStrictMode,reactMode:config.experimental.reactMode,optimizeFonts:config.optimizeFonts,optimizeImages:config.experimental.optimizeImages,optimizeCss:config.experimental.optimizeCss,scrollRestoration:config.experimental.scrollRestoration,basePath:config.basePath,pageEnv:config.experimental.pageEnv,excludeDefaultMomentLocales:config.excludeDefaultMomentLocales,assetPrefix:config.assetPrefix,disableOptimizedLoading:config.experimental.disableOptimizedLoading,target,reactProductionProfiling,webpack:!!config.webpack,hasRewrites});const cache={type:'filesystem',// Includes:
156// - Next.js version
157// - next.config.js keys that affect compilation
158version:`${"11.0.1"}|${configVars}`,cacheDirectory:_path.default.join(distDir,'cache','webpack')};// Adds `next.config.js` as a buildDependency when custom webpack config is provided
159if(config.webpack&&config.configFile){cache.buildDependencies={config:[config.configFile]};}webpackConfig.cache=cache;if(process.env.NEXT_WEBPACK_LOGGING){const logInfra=process.env.NEXT_WEBPACK_LOGGING.includes('infrastructure');const logProfileClient=process.env.NEXT_WEBPACK_LOGGING.includes('profile-client');const logProfileServer=process.env.NEXT_WEBPACK_LOGGING.includes('profile-server');const logDefault=!logInfra&&!logProfileClient&&!logProfileServer;if(logDefault||logInfra){// @ts-ignore TODO: remove ignore when webpack 5 is stable
160webpackConfig.infrastructureLogging={level:'verbose',debug:/FileSystemInfo/};}if(logDefault||logProfileClient&&!isServer||logProfileServer&&isServer){webpackConfig.plugins.push(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
161logging:logDefault?'log':'verbose'}));});});}if(logProfileClient&&!isServer||logProfileServer&&isServer){webpackConfig.plugins.push(new _webpack.webpack.ProgressPlugin({// @ts-ignore TODO: remove ignore when webpack 5 is stable
162profile:true}));webpackConfig.profile=true;}}}webpackConfig=await(0,_config.build)(webpackConfig,{rootDirectory:dir,customAppFile,isDevelopment:dev,isServer,assetPrefix:config.assetPrefix||'',sassOptions:config.sassOptions,productionBrowserSourceMaps:config.productionBrowserSourceMaps,future:config.future,isCraCompat:config.experimental.craCompat});let originalDevtool=webpackConfig.devtool;if(typeof config.webpack==='function'){webpackConfig=config.webpack(webpackConfig,{dir,dev,isServer,buildId,config,defaultLoaders,totalPages,webpack:_webpack.webpack});if(!webpackConfig){throw new Error('Webpack config is undefined. You may have forgot to return properly from within the "webpack" method of your next.config.js.\n'+'See more info here https://nextjs.org/docs/messages/undefined-webpack-config');}if(dev&&originalDevtool!==webpackConfig.devtool){webpackConfig.devtool=originalDevtool;devtoolRevertWarning(originalDevtool);}if(typeof webpackConfig.then==='function'){console.warn('> Promise returned in next config. https://nextjs.org/docs/messages/promise-in-next-config');}}if(!config.images.disableStaticImages&&_webpack.isWebpack5){if(!webpackConfig.module){webpackConfig.module={rules:[]};}const hasSvg=webpackConfig.module.rules.some(rule=>'test'in rule&&rule.test instanceof RegExp&&rule.test.test('.svg'));// Exclude svg if the user already defined it in custom
163// webpack config such as `@svgr/webpack` plugin or
164// the `babel-plugin-inline-react-svg` plugin.
165webpackConfig.module.rules.push({test:hasSvg?/\.(png|jpg|jpeg|gif|webp|ico|bmp)$/i:/\.(png|svg|jpg|jpeg|gif|webp|ico|bmp)$/i,loader:'next-image-loader',dependency:{not:['url']},// @ts-ignore
166issuer:{not:_css.regexLikeCss}});}if(config.experimental.craCompat&&(_webpackConfig$module2=webpackConfig.module)!=null&&_webpackConfig$module2.rules&&webpackConfig.plugins){// CRA prevents loading all locales by default
167// https://github.com/facebook/create-react-app/blob/fddce8a9e21bf68f37054586deb0c8636a45f50b/packages/react-scripts/config/webpack.config.js#L721
168webpackConfig.plugins.push(new _webpack.webpack.IgnorePlugin(/^\.\/locale$/,/moment$/));// CRA allows importing non-webpack handled files with file-loader
169// these need to be the last rule to prevent catching other items
170// https://github.com/facebook/create-react-app/blob/fddce8a9e21bf68f37054586deb0c8636a45f50b/packages/react-scripts/config/webpack.config.js#L594
171const fileLoaderExclude=[/\.(js|mjs|jsx|ts|tsx|json)$/];const fileLoader=_webpack.isWebpack5?{exclude:fileLoaderExclude,issuer:fileLoaderExclude,type:'asset/resource',generator:{publicPath:'/_next/',filename:'static/media/[name].[hash:8].[ext]'}}:{loader:require.resolve('next/dist/compiled/file-loader'),// Exclude `js` files to keep "css" loader working as it injects
172// its runtime that would otherwise be processed through "file" loader.
173// Also exclude `html` and `json` extensions so they get processed
174// by webpacks internal loaders.
175exclude:fileLoaderExclude,issuer:fileLoaderExclude,options:{publicPath:'/_next/static/media',outputPath:'static/media',name:'[name].[hash:8].[ext]'}};const topRules=[];const innerRules=[];for(const rule of webpackConfig.module.rules){if(rule.resolve){topRules.push(rule);}else{if(rule.oneOf&&!(rule.test||rule.exclude||rule.resource||rule.issuer)){rule.oneOf.forEach(r=>innerRules.push(r));}else{innerRules.push(rule);}}}webpackConfig.module.rules=[...topRules,{oneOf:[...innerRules,fileLoader]}];}// Backwards compat with webpack-dev-middleware options object
176if(typeof config.webpackDevMiddleware==='function'){const options=config.webpackDevMiddleware({watchOptions:webpackConfig.watchOptions});if(options.watchOptions){webpackConfig.watchOptions=options.watchOptions;}}function canMatchCss(rule){if(!rule){return false;}const fileNames=['/tmp/test.css','/tmp/test.scss','/tmp/test.sass','/tmp/test.less','/tmp/test.styl'];if(rule instanceof RegExp&&fileNames.some(input=>rule.test(input))){return true;}if(typeof rule==='function'){if(fileNames.some(input=>{try{if(rule(input)){return true;}}catch(_){}return false;})){return true;}}if(Array.isArray(rule)&&rule.some(canMatchCss)){return true;}return false;}const hasUserCssConfig=(_webpackConfig$module3=(_webpackConfig$module4=webpackConfig.module)==null?void 0:_webpackConfig$module4.rules.some(rule=>canMatchCss(rule.test)||canMatchCss(rule.include)))!=null?_webpackConfig$module3:false;if(hasUserCssConfig){var _webpackConfig$module5,_webpackConfig$plugin,_webpackConfig$optimi,_webpackConfig$optimi2;// only show warning for one build
177if(isServer){console.warn(_chalk.default.yellow.bold('Warning: ')+_chalk.default.bold('Built-in CSS support is being disabled due to custom CSS configuration being detected.\n')+'See here for more info: https://nextjs.org/docs/messages/built-in-css-disabled\n');}if((_webpackConfig$module5=webpackConfig.module)!=null&&_webpackConfig$module5.rules.length){// Remove default CSS Loader
178webpackConfig.module.rules=webpackConfig.module.rules.filter(r=>{var _r$oneOf,_r$oneOf$;return!(typeof((_r$oneOf=r.oneOf)==null?void 0:(_r$oneOf$=_r$oneOf[0])==null?void 0:_r$oneOf$.options)==='object'&&r.oneOf[0].options.__next_css_remove===true);});}if((_webpackConfig$plugin=webpackConfig.plugins)!=null&&_webpackConfig$plugin.length){// Disable CSS Extraction Plugin
179webpackConfig.plugins=webpackConfig.plugins.filter(p=>p.__next_css_remove!==true);}if((_webpackConfig$optimi=webpackConfig.optimization)!=null&&(_webpackConfig$optimi2=_webpackConfig$optimi.minimizer)!=null&&_webpackConfig$optimi2.length){// Disable CSS Minifier
180webpackConfig.optimization.minimizer=webpackConfig.optimization.minimizer.filter(e=>e.__next_css_remove!==true);}}else if(!config.future.strictPostcssConfiguration){await(0,_overrideCssConfiguration.__overrideCssConfiguration)(dir,!dev,webpackConfig);}// Inject missing React Refresh loaders so that development mode is fast:
181if(hasReactRefresh){attachReactRefresh(webpackConfig,defaultLoaders.babel);}// check if using @zeit/next-typescript and show warning
182if(isServer&&webpackConfig.module&&Array.isArray(webpackConfig.module.rules)){let foundTsRule=false;webpackConfig.module.rules=webpackConfig.module.rules.filter(rule=>{if(!(rule.test instanceof RegExp))return true;if('noop.ts'.match(rule.test)&&!'noop.js'.match(rule.test)){// remove if it matches @zeit/next-typescript
183foundTsRule=rule.use===defaultLoaders.babel;return!foundTsRule;}return true;});if(foundTsRule){console.warn('\n@zeit/next-typescript is no longer needed since Next.js has built-in support for TypeScript now. Please remove it from your next.config.js and your .babelrc\n');}}// Patch `@zeit/next-sass`, `@zeit/next-less`, `@zeit/next-stylus` for compatibility
184if(webpackConfig.module&&Array.isArray(webpackConfig.module.rules)){;[].forEach.call(webpackConfig.module.rules,function(rule){if(!(rule.test instanceof RegExp&&Array.isArray(rule.use))){return;}const isSass=rule.test.source==='\\.scss$'||rule.test.source==='\\.sass$';const isLess=rule.test.source==='\\.less$';const isCss=rule.test.source==='\\.css$';const isStylus=rule.test.source==='\\.styl$';// Check if the rule we're iterating over applies to Sass, Less, or CSS
185if(!(isSass||isLess||isCss||isStylus)){return;};[].forEach.call(rule.use,function(use){if(!(use&&typeof use==='object'&&(// Identify use statements only pertaining to `css-loader`
186use.loader==='css-loader'||use.loader==='css-loader/locals')&&use.options&&typeof use.options==='object'&&(// The `minimize` property is a good heuristic that we need to
187// perform this hack. The `minimize` property was only valid on
188// old `css-loader` versions. Custom setups (that aren't next-sass,
189// next-less or next-stylus) likely have the newer version.
190// We still handle this gracefully below.
191Object.prototype.hasOwnProperty.call(use.options,'minimize')||Object.prototype.hasOwnProperty.call(use.options,'exportOnlyLocals')))){return;}// Try to monkey patch within a try-catch. We shouldn't fail the build
192// if we cannot pull this off.
193// The user may not even be using the `next-sass` or `next-less` or
194// `next-stylus` plugins.
195// If it does work, great!
196try{// Resolve the version of `@zeit/next-css` as depended on by the Sass,
197// Less or Stylus plugin.
198const correctNextCss=require.resolve('@zeit/next-css',{paths:[isCss?// Resolve `@zeit/next-css` from the base directory
199dir:// Else, resolve it from the specific plugins
200require.resolve(isSass?'@zeit/next-sass':isLess?'@zeit/next-less':isStylus?'@zeit/next-stylus':'next')]});// If we found `@zeit/next-css` ...
201if(correctNextCss){// ... resolve the version of `css-loader` shipped with that
202// package instead of whichever was hoisted highest in your
203// `node_modules` tree.
204const correctCssLoader=require.resolve(use.loader,{paths:[correctNextCss]});if(correctCssLoader){// We saved the user from a failed build!
205use.loader=correctCssLoader;}}}catch(_){// The error is not required to be handled.
206}});});}// Backwards compat for `main.js` entry key
207// and setup of dependencies between entries
208// we can't do that in the initial entry for
209// backward-compat reasons
210const originalEntry=webpackConfig.entry;if(typeof originalEntry!=='undefined'){const updatedEntry=async()=>{const entry=typeof originalEntry==='function'?await originalEntry():originalEntry;// Server compilation doesn't have main.js
211if(clientEntries&&Array.isArray(entry['main.js'])&&entry['main.js'].length>0){const originalFile=clientEntries[_constants2.CLIENT_STATIC_FILES_RUNTIME_MAIN];entry[_constants2.CLIENT_STATIC_FILES_RUNTIME_MAIN]=[...entry['main.js'],originalFile];}delete entry['main.js'];if(_webpack.isWebpack5&&!isServer){for(const name of Object.keys(entry)){if(name==='polyfills'||name==='main'||name==='amp'||name==='react-refresh')continue;const dependOn=name.startsWith('pages/')&&name!=='pages/_app'?'pages/_app':'main';const old=entry[name];if(typeof old==='object'&&!Array.isArray(old)){entry[name]={dependOn,...old};}else{entry[name]={import:old,dependOn};}}}return entry;};// @ts-ignore webpack 5 typings needed
212webpackConfig.entry=updatedEntry;}if(!dev){// entry is always a function
213webpackConfig.entry=await webpackConfig.entry();}return webpackConfig;}
214//# sourceMappingURL=webpack-config.js.map
\No newline at end of file