我正在开发一个使用 next.js (^9.1.1) 和 @zeit/next-less (^1.0.1) 的 Web 应用程序。我正在努力提高这个应用程序的性能。我正在使用 LightHouse 来衡量性能。
LightHouse 机会部分显示了这一点 -
chrome 开发工具的覆盖部分显示 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
我希望这会有所帮助。
关于javascript - 如何减小next.js中style.chunk.css的大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60332917/