I occasionally use Next.js templates when creating websites for clients as more than often than not you can find a template to fit the branding and target audience of the client’s website.
(Although I have to say that there are many more templates available for Gatsby powered sites.. maybe the reason for this is that developers looking to create a fully static site favour Gatsby.js whilst those who need a more hybrid solution including server-side props favour Next.js)
As anyone who has purchased a template before using platforms such as themeforest will know, they are shipped with a large amount of components and pages that you will probably not need - personally I only use around 10% of the components and then I customise the rest according to the clients’ preferences.
The problem that arises after you have removed all the components and pages that you don't need is that you will usually be left with a huge amount of unused CSS which can bloat the bundle size.
Solution
The solution to this issue is extremely straightforward.
I use the PurgeCSS library to remove all the unused CSS in my Next.js projects which could not be easier to integrate.
Firstly install the following packages
npm install @fullhuman/postcss-purgecss postcss-flexbugs-fixes postcss-preset-env
Create a
postcss.config.js
file in the root of the projectCopy the following code into the
postcss.config.js
file
module.exports = { plugins: [ 'postcss-flexbugs-fixes', [ 'postcss-preset-env', { autoprefixer: { flexbox: 'no-2009', }, stage: 3, features: { 'custom-properties': false, }, }, ], [ '@fullhuman/postcss-purgecss', { content: [ './pages/**/*.{js,jsx,ts,tsx}', './components/**/*.{js,jsx,ts,tsx}', ], defaultExtractor: (content) => content.match(/[\w-/:]+(?<!:)/g) || [], safelist: ['html', 'body'], }, ], ], };
Now when you npm run build
in your Next.js project you will see vastly reduced.css files in your .next build.