javascript - 如何减小next.js中style.chunk.css的大小?

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

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

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

LightHouse opportunity Section

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

Coverage section of chrome dev tools

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

最佳答案

您可以使用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

我希望这会有所帮助。

关于javascript - 如何减小next.js中style.chunk.css的大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60332917/

相关文章:

javascript - 如何使用 Promise.all 解构动态数量的异步调用的结果

javascript - 找出对象是否具有相同的键

Next.js 使用 _app.js 和 _document.js

css - 尝试在 css 元素中加载背景图像时出现模块解析错误

javascript - 如何在 ReactJS 中的 Whatsapp 上共享带有文本的图像?

javascript - 显示 : fullscreen doesn't work on manifest json

javascript - 从ajax数据设置App

reactjs - React Hook 表单属性 'type' 在类型 'Merge<FieldError, FieldErrorsImpl<DeepRequired<any>>>' 中缺失,但在类型 'FieldError' 中需要

google-analytics - Google 跟踪代码管理器在单页应用程序中重新创建相同的标记

javascript - 如何使用 javascript 检测内联链接?