DEV Community

Cover image for Nuxt3 LCP Advanced optimizations with pnpm
Domenik Reitzner
Domenik Reitzner

Posted on

Nuxt3 LCP Advanced optimizations with pnpm

This is just a quick one (I promise). 😉

The problem

As I was reading through the nuxt docs about LCP optimisation and tried implementing it, I hit a wall. 🧱

📘 docs link

So here to everyone who has the same issue that I had.

We are using pnpm as our package manager, so the path to the entry.js doesn't look like

node_modules/nuxt/dist/app/entry.js

but more like

node_modules/.pnpm/nuxt@3.12.4_@parcel+watcher@2.4.1_@types+node@18.19.41_eslint@8.57.0_ioredis@5.4.1_magicast@0_sp6oxyoamdsk3zyrb4wztbq7li/node_modules/nuxt/dist/app/entry.js

The solution

To hardcode this path will cause an issue as soon as you update any package that is in that pathname.

To circumvent this you can update the hook to do the following:

import { readdirSync } from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';

export default defineNuxtConfig({
  hooks: {
    'build:manifest': (manifest) => {
      // find the app entry, css list
      const baseModulesFolder = path.dirname(fileURLToPath(import.meta.url)) + '/node_modules/.pnpm/';
      const nuxtFolder = readdirSync(baseModulesFolder).find((file) => typeof file === 'string' && file.startsWith('nuxt@'));
      const entryFilePath = `node_modules/.pnpm/${nuxtFolder}/node_modules/nuxt/dist/app/entry.js`;

      const css = manifest[entryFilePath]?.css;
      if (css) {
        // start from the end of the array and go to the beginning
        for (let i = css.length - 1; i >= 0; i--) {
          // if it starts with 'entry', remove it from the list
          if (css[i].startsWith('entry')) css.splice(i, 1);
        }
      }
    },
  },
})
Enter fullscreen mode Exit fullscreen mode

I hope this helps anyone.

Have a great day and keep on coding 🧑‍💻

Top comments (0)