【问题标题】:How to reduce the size of style.chunk.css in next.js?如何减小 next.js 中 style.chunk.css 的大小?
【发布时间】:2020-06-05 13:04:45
【问题描述】:

我正在开发一个使用 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 -

我有两个问题: 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,
);

【问题讨论】:

  • 您能否使用 CSS 模块实现这一点?我的样式不适用,因为 purgeCss 模块无法识别 CSS 模块

标签: javascript next.js progressive-web-apps lighthouse


【解决方案1】:

你可以使用next-purgecss插件

安装

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

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

  • 下一个CSS
  • next-less
  • 下一个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

我希望这会有所帮助。

【讨论】:

  • 非常感谢您的帮助。 purgeCSS 在开发模式下工作正常,但在生产模式下,样式不适用。我们如何解决这个问题?
  • 我已经为生产添加了配置
  • 我也在做同样的事情,但是样式仍然没有添加到生产版本中。我正在使用 next-less 并将 cssModules 标志设置为 true。
  • 当我运行“next start”时,没有应用任何样式。
  • 我已经在问题中添加了我的配置文件。
猜你喜欢
  • 2022-01-03
  • 2021-10-26
  • 2011-09-03
  • 2016-01-17
  • 2011-09-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多