Supported Browsers
Next.js 支持现代浏览器,无需配置。
- Chrome 111+
- Edge 111+
- Firefox 111+
- Safari 16.4+
Browserslist
如果你想针对特定的浏览器或特性,Next.js 支持在 package.json 文件中配置 Browserslist。Next.js 默认使用以下 Browserslist 配置:
package.json
{
"browserslist": ["chrome 111", "edge 111", "firefox 111", "safari 16.4"]
}Polyfills
我们注入了广泛使用的 polyfills,包括:
- fetch() — 替代:
whatwg-fetch和unfetch。 - URL — 替代:
url包(Node.js API)。 - Object.assign() — 替代:
object-assign、object.assign和core-js/object/assign。
如果你的任何依赖项包含这些 polyfills,它们将自动从生产构建中消除,以避免重复。
此外,为了减少 bundle 大小,Next.js 只会为需要它们的浏览器加载这些 polyfills。全球大多数网络流量不会下载这些 polyfills。
自定义 Polyfills
如果你自己的代码或任何外部 npm 依赖项需要目标浏览器不支持的特性(例如 IE 11),你需要自己添加 polyfills。
在 App Router 中
要包含 polyfills,你可以在 instrumentation-client.js 文件中导入它们。
instrumentation-client.ts
import './polyfills'在 Pages Router 中
在这种情况下,你应该在自定义 <App> 或单个组件中为你需要的特定 polyfill 添加顶层导入。
pages/_app.tsx
TypeScript
import './polyfills'
import type { AppProps } from 'next/app'
export default function MyApp({ Component, pageProps }: AppProps) {
return <Component {...pageProps} />
}条件加载 polyfills
最佳方法是将不支持的特性隔离到特定的 UI 部分,并在需要时有条件地加载 polyfill。
hooks/analytics.ts
TypeScript
import { useCallback } from 'react'
export const useAnalytics = () => {
const tracker = useCallback(async (data: unknown) => {
if (!('structuredClone' in globalThis)) {
import('polyfills/structured-clone').then((mod) => {
globalThis.structuredClone = mod.default
})
}
/* 执行一些使用 structured clone 的工作 */
}, [])
return tracker
}JavaScript 语言特性
Next.js 允许你开箱即用地使用最新的 JavaScript 特性。除了 ES6 特性之外,Next.js 还支持:
- Async/await(ES2017)
- Object Rest/Spread Properties(ES2018)
- Dynamic
import()(ES2020) - Optional Chaining(ES2020)
- Nullish Coalescing(ES2020)
- Class Fields 和 Static Properties(ES2022)
- 以及更多!
TypeScript 特性
Next.js 内置了 TypeScript 支持。在此了解更多。
自定义 Babel 配置(高级)
你可以自定义 babel 配置。在此了解更多。