javascript - 如何减小 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 -
我有两个问题: 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
我希望这有帮助。
推荐阅读
- mysql - Spring Integration:使用 jdbc 出站网关在数据库中插入记录时出错
- javascript - 为什么我的图像不断覆盖自身而不是在 for 循环中显示每个图像?
- automated-tests - 基于窗口的应用程序的自动化测试
- java - 从 TFS 2015 中的发布定义执行 Selenium java 脚本
- python - python变量未使用打印函数定义
- java - 如何遍历LinkedTreeMap的所有值
? - sql-server - SQL Server 2016 中的函数式选项?
- angularjs - 使用 ng-include 时 css 在子主题中不起作用
- android - 毕加索自动旋转从相机拍摄的照片,但不旋转从互联网下载的图像
- mongodb - MongoDB - 获取用户制作的记录