Next.js 13、MUI、transpilePackages 和 modularizeImports

Mar*_*son 6 material-ui next.js next.js13

我的项目是使用TurborepoMUI 的单一存储库。我正在使用Next.js 13并且想优化性能。我发现一篇文章,其中他们使用新的 transpilePackages 和 modularizeImports 属性来优化应用程序中的导入(请参阅此处)。我不知道如何设置 next.config.js (文章中的过程不起作用)。

如果我按照文章设置next.config.js。也就是说,我将 @mui 库添加到 transpilePackages 参数中,然后使用与文章中相同的参数来 modulizeImports:

{
    "@mui/material/?(((\\w*)?/?)*)": {
        transform: "@mui/material/{{ matches.[1] }}/{{member}}",
    },
    "@mui/icons-material/?(((\\w*)?/?)*)": {
        transform: "@mui/icons-material/{{ matches.[1] }}/{{member}}",
    },
}
Run Code Online (Sandbox Code Playgroud)

如果我从 @mui/material 导入 css 或样式,我会收到模块未找到错误:

https://nextjs.org/docs/messages/module-not-found
wait  - compiling /_error (client and server)...
error - ../../packages/core/icons/Icon.tsx:14:0
Module not found: Can't resolve '@mui/material/css'
import { css, styled } from "@mui/material";
Run Code Online (Sandbox Code Playgroud)

我尝试了很多方法并设法得到另一个类似的错误,但是使用 alpha 函数(以及其他一些函数)。我假设 moduleizeImports 参数不正确,但我不知道它应该如何正确。

小智 0

您可以尝试将以下内容添加到您的 .next.config.js 文件中吗:

transpilePackages: ["@mui/material/css"]

示例 .next.config.js

/** @type {import('next').NextConfig} */
const nextConfig = {
  reactStrictMode: true,
  transpilePackages: ["@mui/material/css", etc..]
};

module.exports = nextConfig;

Run Code Online (Sandbox Code Playgroud)