transpilePackages
自动转译并打包来自本地包(如 monorepo)或外部依赖项(node_modules)的依赖项。
使用 transpilePackages 来编译并打包依赖项,而不是将其视为未经改动的运行时代码。值是包名,包括像 @scope/pkg 这样的作用域名称。不支持路径和 glob 模式。
next.config.js
/** @type {import('next').NextConfig} */
const nextConfig = {
transpilePackages: ['package-name', '@scope/pkg'],
}
module.exports = nextConfig这取代了 next-transpile-modules 包。
何时需要它#
在两种 router 下,Turbopack 都会自动转译 monorepo 中的工作区包(npm、pnpm 或 Yarn 工作区)。Webpack 对 App Router 也是如此。在以下情况下,请将包添加到 transpilePackages:
node_modules依赖项附带原始 TypeScript 或 JSX。 Next.js 默认不会编译node_modules内的代码。列出该包即可选择加入,或者你可以将该包构建为纯 JavaScript,并将其main/exports指向编译后的输出。- 你使用 webpack 为 Pages Router 构建,且依赖项的源代码位于 next 应用目录之外。 例如,同一 monorepo 中的
apps/web应用导入packages/ui。 - 你使用 Pages Router,并希望将某个
node_modules依赖项打包到路由中。 Pages Router 在运行时通过 Node.js 的require加载node_modules中的服务器端依赖项。列出该包可改为将其源代码打包到路由中。除非某个包被列在serverExternalPackages中,否则 App Router 已经会打包 Server Component 和 Route Handler 的依赖项。
小知识:一个包不能同时出现在
transpilePackages和serverExternalPackages中;如果出现,Next.js 会在构建开始时抛出错误。列在optimizePackageImports中的包以及default-transpiled-packages.json中的条目会自动添加;你无需重复列出它们。
版本历史#
| 版本 | 变更 |
|---|---|
v13.0.0 | 新增 transpilePackages。 |