首页 > 解决方案 > 如何减小 next.js 中 style.chunk.css 的大小?

问题描述

我正在开发一个使用 next.js (^9.1.1) 和 @zeit/next-less (^1.0.1) 的 Web 应用程序。我正在努力提高这个应用程序的性能。我正在使用 LightHouse 来衡量性能。

LightHouse 机会部分显示了这一点 -

灯塔机会科

chrome dev tools 的覆盖部分显示 styles.chunk.css 文件中 97.5% 的 CSS 未被使用,我认为这是因为它包含了我的 Next App 几乎所有页面的 CSS -

chrome dev工具的覆盖部分

我有两个问题: 1. 这个 styles.chunk.css 文件是做什么的?2. 如何减小此文件的大小,使其仅包含该特定页面所需的样式?

我曾尝试使用 next-purgecss,但 purgecss 仅在开发模式下工作而不在生产模式下工作,我的配置文件写在下面 -


module.exports = withPlugins(
  [
    withLess(withPurgeCss({
      purgeCssEnabled: ({ dev, isServer }) => (!dev && !isServer),
      cssModules: true,
      cssLoaderOptions: {
        getLocalIdent: (loaderContext, localIdentName, localName, options) => {
          const fileName = path.basename(loaderContext.resourcePath);
          const shoudTransform = canBeTransformed(loaderContext.resourcePath);

          if (!shoudTransform) {
            return localName;
          }
          const name = fileName.replace(/\.[^/.]+$/, '');
          return `${name}___${localName}`;
        },
      },
    })),
    // withBundleAnalyzer({}),
  ],
  nextConfig,
);

标签: javascriptnext.jsprogressive-web-appslighthouse

解决方案


你可以使用next-purgecss插件

安装

npm install @zeit/next-css next-purgecss --save-dev

注意:next-purgecss需要以下 css next 插件之一:

  • 下一个 CSS
  • 下一个
  • 下一个sass

编辑 next.config.js

// next.config.js
const withCss = require('@zeit/next-css')
const withPurgeCss = require('next-purgecss')

module.exports = withCss(withPurgeCss())

默认情况下,next-purgecss无论构建环境如何,都将始终删除未使用的 CSS。

编辑:

生产用

// next.config.js
module.exports = withCss(
  withPurgeCss({
    // Only enable PurgeCSS for client-side production builds
    purgeCssEnabled: ({ dev, isServer }) => (!dev && !isServer) 
  })
)

更多信息在这里:https ://www.npmjs.com/package/next-purgecss

我希望这有帮助。


推荐阅读