Next.js 15 App Router兼容旧浏览器(Chrome59/Opera46)方案咨询
Next.js 15 App Router 兼容旧浏览器(Chrome 59/Opera 46)的解决方案
1. 配置SWC编译目标(替代tsconfig.target)
Next.js 13+ 默认使用SWC编译,tsconfig.json里的compilerOptions.target仅用于TypeScript类型检查,不影响最终编译输出。需在next.config.js中直接配置SWC的编译目标:
/** @type {import('next').NextConfig} */ const nextConfig = { compiler: { swcOptions: { jsc: { target: 'es2017', // Chrome 59/Opera 46原生支持ES2017核心特性 parser: { syntax: 'typescript', jsx: true, }, }, }, }, }; module.exports = nextConfig;
2. 让SWC读取Browserslist配置
之前的Browserslist配置无效,是因为SWC默认未启用该规则。先在package.json中明确兼容目标:
{ "browserslist": [ "Chrome >= 59", "Opera >= 46" ] }
再在next.config.js中开启SWC对Browserslist的支持:
const nextConfig = { // ...其他配置 experimental: { browsersListForSwc: true, // 让SWC根据Browserslist自动调整编译逻辑 }, };
3. 全局注入必要Polyfill
针对globalThis is not defined和Unexpected token ...错误,需注入对应Polyfill:
方法1:通过Webpack自动注入
用Webpack的ProvidePlugin自动挂载Polyfill,无需手动在组件中引入:
const webpack = require('webpack'); const nextConfig = { // ...其他配置 webpack: (config) => { config.plugins.push( new webpack.ProvidePlugin({ globalThis: ['core-js/es/global-this', 'default'], Object: ['core-js/es/object', 'default'], Array: ['core-js/es/array', 'default'], }) ); return config; }, };
方法2:在根布局手动引入
在app/layout.tsx最顶部引入Polyfill(确保在任何组件渲染前加载):
import 'core-js/es/global-this'; import 'core-js/es/object/assign'; import 'core-js/es/array/from'; export default function RootLayout({ children }) { return ( <html lang="zh-CN"> <body>{children}</body> </html> ); }
注意:需先安装依赖:npm install core-js
4. 转译第三方依赖
部分node_modules中的包可能使用了未转译的ESNext语法,需让Next.js强制转译这些包。在next.config.js中配置:
const nextConfig = { // ...其他配置 transpilePackages: ['依赖包名称1', '依赖包名称2'], // 替换为实际报错的依赖包名 };
可根据构建报错信息定位需要转译的包,逐个添加到列表中。
5. 验证兼容性
构建项目后,检查.next/static/目录下的输出JS文件:
- 搜索
globalThis,确认已被替换为Polyfill代码 - 检查是否存在对象扩展运算符
...,确认已被转译为ES5兼容的赋值逻辑
也可直接在Chrome 59/Opera 46中打开项目,验证错误是否消失。
内容的提问来源于stack exchange,提问作者Mil
相关产品推荐
相关产品推荐

