Next.js 10升12后next.config.js无效选项错误及解决
Next.js 10 升级到 12 配置错误修复方案
核心问题分析
错误源于Next.js 12移除了大量旧版配置项、内置了CSS/Sass支持,同时部分第三方插件不再兼容。以下是针对性修复步骤:
步骤1:清理过时依赖
删除项目中不再需要的旧插件:
npm uninstall @zeit/next-css @zeit/next-sass # 或使用 yarn yarn remove @zeit/next-css @zeit/next-sass
确保next-compose-plugins、next-optimized-images等插件更新到兼容Next.js 12的版本;若next-optimized-images无法兼容,建议替换为Next.js内置的图片优化方案(通过images配置项实现)。
步骤2:修改next.config.js配置
以下是修复后的完整配置,关键修改点已标注:
const composePlugins = require('next-compose-plugins'); const optimizedImages = require('next-optimized-images'); const transpileModules = require('next-transpile-modules'); const path = require('path'); const readFileSync = require('jsonfile').readFileSync; const realpathSync = require('fs').realpathSync; const resolve = require('resolve'); const LodashWebpackPlugin = require('lodash-webpack-plugin'); // 修正插件导入方式 const appDirectory = realpathSync(process.cwd()); const resolveApp = relativePath => path.resolve(appDirectory, relativePath); const paths = require(resolveApp('config/paths')); const packageJson = readFileSync(paths.appPackageJson); const root = packageJson.homepage; const dev = !(process.env.NODE_ENV ? process.env.NODE_ENV.indexOf(`production`) + 1 : false); const shouldUseSourceMap = process.env.GENERATE_SOURCEMAP !== 'false'; const withBundleAnalyzer = require('@next/bundle-analyzer')({ enabled: process.env.ANALYZE === 'true', }); let nextEnv = process.env.NEXT_ENV; for (let argument of process.argv) { if (argument.indexOf(`--next-env=`) > -1) { nextEnv = argument.split(`=`)[1]; } } const nextConfig = { async redirects() { return [ { source: '/', destination: '/forbusiness', basePath: false, permanent: false, }, ] }, assetPrefix: '/forbusiness', basePath: '/forbusiness', images: { domains: ['att.com', 'directv.com'], }, // 替换为Next.js 12支持的devIndicators配置 devIndicators: { buildActivity: true, buildActivityPosition: 'bottom-right' }, distDir: `dist`, serverRuntimeConfig: { devProxy: process.env.APP_DEV_PROXY, nextEnv, popCacheInt: process.env.UF_CACHE_INT, pxy: process.env.APP_HTTP_PROXY, solrEnv: process.env.IDP_SOLR_ENV, }, publicRuntimeConfig: { NEXT_PUBLIC_ENV: process.env.NEXT_PUBLIC_ENV, prod: !dev, root, local: process.env.ENV, NEXT_PUBLIC_MICROPROPERTIES_OID: process.env.NEXT_PUBLIC_MICROPROPERTIES_OID, NEXT_PUBLIC_MICROPROPERTIES_RECORD_TYPE: process.env.NEXT_PUBLIC_MICROPROPERTIES_RECORD_TYPE, NEXT_PUBLIC_MICROPROPERTIES_ORG_BASE_URL: process.env.NEXT_PUBLIC_MICROPROPERTIES_ORG_BASE_URL }, generateBuildId: async () => { return packageJson.version; }, // 迁移Sass配置到Next.js内置选项 sassOptions: { outputStyle: 'compressed', precision: 5, sourceMap: shouldUseSourceMap }, // 启用内置CSS Modules支持 cssModules: true, cssLoaderOptions: { camelCase: true, import: true, importLoaders: 1, localIdentName: dev ? '_[local]_[hash:base64:5]' : `_[hash:base64:5]`, minimize: true, sourceMap: shouldUseSourceMap, }, webpack: (config, options) => { const {dir, isServer} = options; const newConfig = {...config}; const originalEntry = newConfig.entry; newConfig.externals = []; newConfig.node = { dgram: `empty`, dns: `empty`, fs: `empty`, net: `empty`, tls: `empty`, child_process: `empty`, path: 'empty', __dirname: true, }; newConfig.entry = async () => { const entries = await originalEntry(); if ( entries['main.js'] && !entries['main.js'].includes('./src/services/Polyfills/polyfill.js') ) { entries['main.js'].unshift('./src/services/Polyfills/polyfill.js'); } return entries; }; newConfig.output.jsonpFunction = `salesJsonp`; if (isServer) { newConfig.externals.push((context, request, callback) => { resolve( request, {basedir: dir, preserveSymlinks: true}, (err, res) => { if (err) { return callback(); } if ( res.match(/node_modules[/\\].*\.js/) && !res.match(/node_modules[/\\]webpack/) && !res.match(/node_modules[/\\]@idp/) && !res.match(/node_modules[/\\]@video/) ) { return callback(null, `commonjs ${request}`); } callback(); } ); }); } // 将Lodash插件添加到webpack插件列表 newConfig.plugins.push(new LodashWebpackPlugin({ caching: true, exotics: true, })); newConfig.module.rules.push({ test: /\.(woff|woff2|eot|ttf|otf)$/, use: [ { loader: 'url-loader', options: { limit: 100000, fallback: 'file-loader', outputPath: `./static/fonts/`, }, }, ], }); newConfig.plugins = newConfig.plugins.filter(plugin => { if (plugin.constructor.name === 'ForkTsCheckerWebpackPlugin') return false; return true; }); return newConfig; }, }; module.exports = composePlugins( [ [optimizedImages, { svgo: { plugins: [ { removeComments: true, cleanupAttrs: true, inlineStyles: true, minifyStyles: true, }, ], }, }], [withBundleAnalyzer, {}], ], nextConfig );
关键修改说明
- 移除过时CSS/Sass插件:Next.js 12内置了CSS和Sass支持,直接通过
cssModules、cssLoaderOptions、sassOptions配置即可,无需依赖第三方插件。 - 调整Lodash插件用法:将
lodash-webpack-plugin从composePlugins中移除,改为在webpack配置的plugins数组中实例化添加,避免无效配置项污染根配置。 - 替换不支持的配置:删除
devIndicators.autoPrerender,改用Next.js 12支持的buildActivity和buildActivityPosition属性。 - 清理无效根配置项:原配置中
caching、exotics、svgo等属性是插件内部配置,已迁移到对应插件或webpack配置中,不再出现在根配置里。 - 修复i18n为null问题:若项目不需要国际化,直接删除
i18n配置;若需要,需配置为包含locales、defaultLocale等属性的对象。
内容的提问来源于stack exchange,提问作者Yeshwanth Kumar
相关产品推荐
相关产品推荐

