npm as Drupal's front-end package manager

Topics

Every other part of a modern Drupal site has a package manager. PHP dependencies have Composer: a lock file, a resolved dependency graph, and composer audit to tell you when something you depend on has a published advisory. Front-end libraries have none of that. A Drupal site that pulls in Leaflet, PhotoSwipe, Day.js or Bootstrap typically has no machine-readable record of which versions are installed, and no way to be told when one of them has a CVE.

That gap is the subject of this article. What follows is an approach I now run on my own sites and a number of client ones: npm is the only place front-end libraries come from, and *.libraries.yml is the only place they are declared. No files committed to the repository, no /libraries folder assembled by hand, and no scripts loaded from a CDN. The result is that npm audit covers your front end the way composer audit covers your back end.

The point is not that Drupal needs a front-end package manager of its own. It already has one available to it, the same one everybody else uses. What it needs is a way to fit the standard front-end workflow — npm, a lock file, node dependencies, a build — into the way Drupal sites are actually assembled and deployed, so that using it does not mean working around the asset layer or abandoning it.

First, though, it is worth being precise about why the current options are unsatisfying, because each of them is defensible in isolation. It is the thing they all leave out that matters.

The three ways to get a library into Drupal today

Composer. This is really two different things wearing the same coat, and they fail differently.

The first is asset-packagist. You add oomphinc/composer-installers-extender, register the asset-packagist repository, and require packages like npm-asset/leaflet. Composer places them in /libraries, exactly where contrib modules look. It is the most defensible of all the options here and the one most teams reach for. But asset-packagist is a third-party bridge that mirrors npm into Composer package names: you depend on that service being up and accurate, you get the published package rather than a build of it, and the advisory data that makes composer audit worth running simply does not exist for npm-asset/*. You get a version in composer.lock, which is genuinely better than nothing — but nothing is watching it.

It is also quietly decaying. Drupal core considered adopting it and declined: issue #3198245, which proposed a composer run enable-asset-packagist helper, was closed won’t fix in February 2021 on the grounds that “using composer as npm replacement is a bad idea” and that asset-packagist’s “reliability is questionable”. Worse, the glue it depends on has since gone: oomphinc/composer-installers-extender, the package that teaches Composer where to put npm-asset/* packages, is marked abandoned on Packagist, its last release 2.0.1 in December 2021. You can still use this route today, but you are building on something its own ecosystem has stopped maintaining.

The second is a hand-written repository entry, which is what you fall back to when a library is not on asset-packagist at all. You add a {"type": "package"} block to composer.json describing the package yourself: its name, its version, and a dist URL pointing at a release archive. Composer dutifully installs it. The catch is in who authored that metadata. You typed the version string, so it is correct only for as long as you keep typing it correctly; you chose the dist URL, so you own it if the upstream project moves or retires it. Composer will faithfully reinstall exactly what you described, forever, and will never tell you that a newer release exists or that the one you pinned has an advisory against it. In tracking terms this is closer to committing the files than it looks — you have simply moved the hand-maintained record from a folder into composer.json.

Both variants share a second problem, and on a real site it is the one you notice first: you get the entire package, not the part you need. Composer unpacks whatever the archive contains straight into your webroot. A published npm package is built for consumers who will run it through a bundler, so it routinely ships the src tree as well as dist, several build formats of the same code, source maps, tests, fixtures, documentation and a folder of example pages. You wanted one minified file and a stylesheet; you installed all of it.

That is partly bloat — megabytes in the repository and the deploy artefact for a library whose useful payload is tens of kilobytes. But the part that should bother you is that it is all sitting under the webroot, served to anyone who asks. Source maps hand back the original source. Example and demo pages are real HTML, in your document root, on your domain, outside any of your application’s own protections. None of it was written with the assumption that it would be publicly reachable on a production site, because in its intended use it never is. You cannot prune it either, because the next composer install restores it.

And then there is the case where Composer cannot help you at all: plenty of packages ship no browser-ready build in the first place. The published tarball holds ES module source, or TypeScript, and assumes the consumer will run it through a bundler, because every consumer the author had in mind does exactly that. There is no dist/thing.min.js to point a library definition at. Sometimes it is subtler and worse: the package does ship .js, but its modules import bare specifiers — import x from 'other-package' — which a browser cannot resolve on its own. The file looks loadable right up until the moment it is loaded.

No package manager answers this on its own, and that includes npm: package managers resolve and install files, they do not compile them. What is missing here is not a better installer but a build step — something that takes the module source the package actually ships and turns it into something a browser can load. Without one, you go looking for a CDN that publishes a bundled version, or you build the file by hand on your laptop and commit the output — which is the committed-files option again, now with an undocumented build step that lives only in your shell history. Either way the package you can install has quietly become a different artefact from the package upstream publishes.

Committing the files to the repository. Download the dist build, drop it in /libraries or your theme, commit it. It always works, it has no external dependency at deploy time, and it is completely reproducible. It is also completely opaque: six months later nobody knows whether leaflet.js in that folder is 1.7.1 or 1.9.4, whether it was modified, or whether the version it came from has since had a security release. Upgrading means repeating the download by hand. In practice these files are committed once and never touched again.

There is a practical cost on top of the opacity, and anyone who has lived with it will recognise the shape. Compiled files are hostile to version control. A minified bundle is one enormous line, so the diff is useless and a merge conflict in it cannot be resolved by reading: two branches that each bumped the same library produce a conflict no human can adjudicate, and the only honest resolution is to discard both sides and rebuild from whichever version you actually meant. Git is being asked to track an artefact as though it were a source, and it has nothing useful to offer. Multiply that across a few libraries and a couple of developers and the repository starts generating work instead of saving it.

It gets worse once the copies stop being central. A library committed inside a module or a theme belongs to that module or theme, and nothing coordinates it with anyone else’s. Two modules can each vendor the same library at different major versions, and Drupal will cheerfully attach both to the same page, because its library system has no notion that they are the same thing — one declares mymodule/chartjs, the other othermodule/charts, and from the outside those are simply two libraries.

What happens next depends on the library. Two scripts claiming the same global means the last one to load wins and the other module is now running against an API it was not written for, often failing in ways that look nothing like a version conflict. A jQuery plugin registering itself twice may leave whichever registration ran last attached to every matching element. And in the best case, where they genuinely do not interfere, you have simply shipped the library twice.

A package manager prevents this by construction. npm and Composer both resolve a dependency graph: two requirements for the same package are reconciled into one installed version, or the install fails and tells you why. Copying files into modules and themes has no graph to resolve — there is nothing to notice the duplication, so nobody does, until something breaks on the one page that happens to use both modules at once.

Referencing an external URL. Point the library at a CDN and let someone else host it. Nothing to install, nothing to commit. In exchange you have added a third party to your site’s runtime critical path, handed them a view of your visitors, and taken on a supply-chain risk that subresource integrity only partly mitigates. For a site with any privacy or availability obligations this is usually the first option ruled out. It also puts the file outside Drupal’s asset pipeline entirely: a URL cannot be aggregated with anything, so every CDN library is a separate request that no amount of configuration will fold into the rest.

What all three leave out

Each of those is a reasonable answer to “how do I get this file onto the page?”. None of them is an answer to the questions you actually need answered over the life of a site:

  • Which version of this library is installed, right now, in production?
  • Has a security advisory been published against it since we installed it?
  • If I upgrade it, what else breaks?
  • How much of what we installed are we actually serving, and what is the rest?
  • Can I answer all of the above without a human reading a folder?

Composer answers those for PHP. npm answers them for JavaScript. Drupal’s front end sits in a gap between the two, and the usual result is a site whose PHP dependencies are patched within days of an advisory and whose JavaScript libraries are whatever was current when the site was built.

This is not a hypothetical concern. The npm advisory database is large, well maintained, and wired into tooling that developers already run. The problem is not that the information is unavailable — it is that Drupal’s front end is not plugged into it.

Who already does this well

In my experience the Drupal sites with genuinely well-managed front ends have one thing in common, and it is not a clever module. They have dedicated front-end developers, and those developers build the way they build everywhere else: npm, a lock file, node dependencies, a build step, the whole ordinary apparatus. They did not find a Drupal answer to this problem. They brought their own and quietly declined to use Drupal’s.

I owe this article to one of them. Max Pogonowski, who I worked with at NSW, is the reason I use Vite at all. He was doing every bit of this as a matter of course — npm, a lock file, a real build — while I was still treating the front end as something Drupal took care of on my behalf. What he showed me was not so much a technique as a standard, and once you have watched the ordinary front-end workflow running properly it becomes very hard to go back to assembling a /libraries folder by hand. Everything that follows is an attempt to make that standard reachable from inside Drupal, rather than alongside it.

He is also darvanen on drupal.org, which means he appears twice more below without my arranging it. Once in the module this whole approach rests on: #3401054, Vite 5 compatibility for drupal/vite, back in 2023. And once asking, in a core issue, the exact question this article is an answer to. The person who got me into this turns out to be standing at both ends of it.

That pattern is worth sitting with, because it says something about where the gap actually is. The method that works is not novel, not Drupal-specific, and not difficult. It is what every JavaScript project of the last decade does by default. Drupal’s front end is badly managed on the sites where nobody is in a position to ignore the conventions — where the person maintaining it is a back-end developer who reasonably assumes the documented path is the right one, and the documented paths are the three above.

So the goal is not to invent something. It is to stop the ordinary thing being awkward enough that only specialists do it, and to make the result legible to Drupal rather than bolted alongside it. A front-end developer should not have to choose between the tooling they know and a site that knows what it is serving.

None of this is a new observation

Before going further it is worth saying plainly that this problem is nine years old and very well understood by people closer to core than I am. Issue #2873160, “Implement core management of 3rd-party FE libraries”, was opened in April 2017 and is still Active, with its most recent comment in May 2026. A hundred and thirty comments; no resolution.

I am in that issue myself, at comment #15 in May 2017. I was not proposing anything grand — just reporting that on one project I was using robloach/component-installer, and naming what bothered me about the alternatives: “the amount of junk that follows along with it. in the form of examples, docs, etc.” What I wanted, I wrote, was that “in my libraries files I just have want is needed an no rubbish.”

Someone liked it. Nobody answered the junk problem. And reading it back now, that scruffy sentence is the same argument this article spends several thousand words making: the library declaration should decide what gets published, and nothing else should come along for the ride. Nine years, and the best I can say is that I can now do it.

Plenty has been tried in between. mile23 proposed in 2017 that yarn at the project root merge each module’s package.json and that *.libraries.yml point at the result. The webpack module does something close to that today. lauriii proposed npm workspaces in 2022, with a script moving assets into /libraries. Libraries Provider adds its own key to *.libraries.yml and resolves assets from a CDN or /libraries; it is now marked “no further development”.

So the shape of the idea is not original. What I have not found proposed is the specific move this one makes: treating the *.libraries.yml declaration itself as the manifest, and resolving its paths directly out of node_modules at build time. The declaration already exists, it already lists exactly the files the site uses, and nothing else in Drupal has a better claim to being the record of what the front end needs.

Why none of it landed

There is one objection that has stopped every version of this, and it deserves stating rather than hiding from. effulgentsia put it plainly in 2022: Node.js cannot become a hard requirement for installing a module, because Automatic Updates and Project Browser have to work on shared hosting where Node.js does not exist. Any approach that needs a build step inherits that problem, and mine needs a build step.

That objection is worth splitting in two, because it is decisive in one case and not the other. Where it holds is Project Browser and Automatic Updates: someone clicking “install” in the Drupal UI on a shared host has no build step available, and no amount of tooling on my side changes that. Where it does not hold is site building, which is most of the work. Shared hosting is a statement about where a site runs, not about where it is built. Build offsite and ship the result — GitHub Actions, GitLab CI, Azure DevOps, whatever you already have — and the shared host receives finished files it never has to compile. Node.js lives on the build runner, where it costs nothing; it never has to exist on the server at all.

That split tends to track experience rather than hosting budget. Inexperienced site builders try to do everything on the server, because that is where the site is. Experienced ones do not build on production for anything — not Composer, and not front-end assets either. So the constraint is real for in-UI installation, and largely self-inflicted everywhere else.

Two things have shifted since. nod_ opened #3568894 in January 2026, prototyping a PHP implementation of npm — merging contrib package.json files and resolving them with npm’s own algorithm, from PHP, with no Node.js anywhere. It is explicitly a prototype, and the summary cheerfully admits as much. But it attacks exactly the right constraint.

And in the one substantive comment on that issue, in May 2026, darvanen — Max again — asks what the benefit of doing it in PHP is “given that Drupal CMS is dropping the shared-hosting requirement” — which, if that holds, removes the obstacle that killed every previous attempt.

Those two efforts are complementary rather than competing, and it is worth being clear about which half each solves. nod_’s prototype answers acquisition: how packages arrive without Node.js. It says nothing yet about how the files then reach a page — darvanen’s first question on the issue is precisely “how do we get these to the frontend?”. What follows here is an answer to that second half: the declaration that already exists, used as the manifest, deciding what gets published and at which version. The two could meet in the middle.

Making libraries.yml the only source of truth

One piece of this is not mine and deserves naming first. drupal/vite is a contributed module that teaches Drupal’s asset system about a Vite build: a library marked vite: true has its assets resolved through the build manifest rather than served from the path written in the YAML, and in development they come from the dev server instead, with hot reloading. It is the bridge between Drupal’s library system and a modern front-end build, and without it none of what follows would be possible. Everything below sits on top of it.

Nor is every plugin in my own config mine. vite-plugin-preserve-drupal-t, by axioteo, keeps Drupal.t() and Drupal.formatPlural() intact through minification, so the calls Drupal’s translation system looks for are still recognisably there in the built output. It is a small thing that is quietly essential on any translated site, and exactly the sort of problem you find out about after shipping rather than before.

The premise is simple. Install front-end libraries with npm, exactly as you would in any other JavaScript project. Declare them in *.libraries.yml as a path into node_modules. Let the build copy what is needed into place. Never commit the files, never reference a CDN, and never maintain a parallel list of dependencies.

What makes that workable is a property of Drupal’s library system that is easy to take for granted: it is YAML. The declarations are plain files on disk with a documented structure, and nothing needs to be running to read them. The Vite plugin globs *.libraries.yml and *.info.yml off the filesystem and parses them in Node — no Drupal bootstrap, no database, no PHP in the build at all. That is the difference between a build you can run anywhere and one that needs a working site to tell it what to do: a CI runner with a checkout and npm ci has everything it needs, and so does a cold clone on a laptop. Drupal’s asset layer deserves credit here rather than blame. It was declarative long before that was fashionable, and being declarative is precisely what makes it usable from outside Drupal.

Adding a package becomes two steps. First, install it as a dev dependency:

npm install -D [email protected]

It is a dev dependency because nothing needs the package once the site is running. The build consumes it and produces something deliverable — a copied file, or a bundle — and that output is what ships. The package itself was an input, not part of the result. If something genuinely were required at runtime you would make it a regular dependency, but in Drupal that case is rare: everything is either copied into place or compiled into your own assets before the site serves a request, so in practice these all end up as dev dependencies.

That distinction is not merely bookkeeping, because it decides what ends up in the deploy artefact. Dev dependencies are precisely the things the artefact can leave out. A multi-stage Docker build installs them in the stage that runs the build and copies only the output into the runtime image; a deploy that installs on the server reaches the same place with npm ci --omit=dev. Either way node_modules is a build-time directory that never ships.

The ratio is lopsided enough to be worth saying out loud. This site’s build consumes 73MB of node_modules and emits about 64KB — the compiled CSS, the copied library files and the manifest — and that 64KB is the entirety of what the runtime image receives. On larger sites I have seen omitting dev dependencies take 120MB off the artefact, which stops being a rounding error once it is pushed to a registry and pulled onto a server on every single release.

It is also the sharpest contrast with committing the files. A committed library is in the repository, and therefore in the artefact, permanently — along with every version of it anyone has ever committed, because git keeps the old copies long after you delete the current one. Here the only things that persist are a line of YAML and a line in a lock file.

The other thing that install decides is how tightly the version is pinned, and it is worth being clear about, because it is easy to reach for the wrong instinct here. The default saves a caret range, ^1.9.4, which allows later patch and minor releases. That sounds alarmingly loose, and in a world without lock files it would be.

But package-lock.json records the exact version actually installed, and npm ci installs precisely that. This is the same arrangement Composer has had all along: the constraint in composer.json expresses what you will accept, composer.lock records what you actually got, and composer install reproduces it exactly. Nobody worries that ^10.3 in a Drupal composer.json makes a deployment unpredictable, because the lock file settles it. npm works the same way. The range is not what makes an install deterministic; the lock file is.

What the range decides is what happens when you deliberately ask for updates. A caret means npm update brings in patch and minor releases — which is where most security fixes live, so letting them through is usually what you want for a front-end library. Adding -E saves the exact version instead and freezes it until you change it by hand. That is the right choice when a version has to match something else: pinning to line this site up with another, reproducing a reported bug, or working around a regression in a later release. It is a deliberate exception, not the default posture.

Either way the lock file is the record, so npm audit is telling the truth about what the site is serving, and a tool like Renovate can raise a pull request when something moves.

Second, declare it in the library definition, pointing at the file inside the package:

leaflet:
  vite: true
  js:
    ../../../../node_modules/leaflet/dist/leaflet.js: { vite: { global: true, copy: ['dist/images/*'] } }
  css:
    component:
      ../../../../node_modules/leaflet/dist/leaflet.css: {}

On the next build, vite-plugin-drupal-libraries reads every *.libraries.yml and *.component.yml across every module, theme and profile, and copies the referenced files to web/libraries/[email protected]/. A path that does not exist stops the build and names the library responsible, rather than producing a page with a missing script.

Note what reaches the webroot: the two files named above, anything those files reference, and the marker images asked for by copy:. References are followed automatically — a url() in the CSS or an asset import in the JS is resolved and copied without being mentioned anywhere, which is just Vite doing what Vite does. copy: is the escape hatch for files that nothing references statically, and Leaflet is a good example of needing one: it assembles its marker URLs at runtime, so no amount of reading the source reveals them.

Everything else stays where it is. Leaflet’s src tree, its source maps, its tests and its reference documentation stay in node_modules, which is a build-time directory the site never serves and which does not go anywhere near the deploy artefact. The declaration is not only the record of what is installed — it is the allowlist of what gets published. Serving a file is a decision someone made in libraries.yml, rather than a side effect of how the upstream project happens to package its releases.

Declaring them has one more consequence worth noting before we get to the configuration: it hands them to Drupal’s own asset pipeline, which is worth more than it sounds. Core aggregates and optimises whatever libraries declare: CssOptimizer strips whitespace and comments, and since 10.1 JsOptimizer re-renders JavaScript through a real parser rather than merely concatenating files end to end. That matters because a dist build is frequently less minified than the name implies. Plenty ship with their licence and version banner deliberately preserved — the library’s own minifier was told to keep it — and some are not minified at all, only bundled. Handing them to Drupal strips what the upstream build left behind and folds them in with everything else, which a file you reference by URL can never be. On this site the served CSS aggregates carry no banner comments whatsoever; whatever the source files shipped with is gone before anything reaches a browser.

That configuration is a single registration, done once, and it is the end of the setup. What never needs touching again is the entry list: adding the tenth library is the same two steps as the first, and vite.config.js does not grow:

import { defineConfig } from 'vite';
import drupalLibraries from 'vite-plugin-drupal-libraries';

export default defineConfig({
  plugins: [
    drupalLibraries(),
  ],
  build: {
    manifest: true,
    outDir: 'web/libraries',
    // web/libraries also holds Composer-installed libraries, so don't
    // empty it; the plugin only removes the folders it made itself.
    emptyOutDir: false,
  },
});

One plugin, not two: drupalLibraries() brings vite-plugin-drupal-npm-libraries with it as a dependency and returns it already configured, so the copying out of node_modules is wired up without appearing in your config. The split is one of responsibility rather than setup — one half reads the YAML and works out what is needed, the other does the copying.

That pair covers packages you install. Your own stylesheets are the other half of the build, and they have their own plugins: vite-plugin-drupal-css for CSS and vite-plugin-drupal-sass for Sass. Vite would compile either without any help, so it is worth being clear about what they add. A Drupal stylesheet is rarely self-contained — it expects a theme’s variables, its mixins, its Tailwind utilities, and on a multi-site build it expects the right theme’s. Both plugins take that from the same .info.yml everything else here reads, so a module’s stylesheet compiles against the theme it will be rendered in without the module having to know which theme that is:

import tailwindcss from '@tailwindcss/vite';
import drupalLibraries from 'vite-plugin-drupal-libraries';
import drupalCss from 'vite-plugin-drupal-css';
import drupalSass from 'vite-plugin-drupal-sass';

const loadPaths = ['node_modules', 'web/themes/custom'];

// Both plugins work out which theme a file belongs to the same way, so they
// take the same two options for it.
const themes = {
  // A module has no theme of its own: name the one its stylesheets should
  // compile against — usually the base theme every subtheme extends.
  moduleTheme: 'base_theme',
  // On a multisite, a module under sites//modules compiles against that
  // site's own theme instead. Keys are site directory names, globs allowed.
  siteThemes: {
    'site-a': 'site_a_theme',
    'site-b': 'site_b_theme',
  },
};

export default defineConfig({
  plugins: [
    drupalLibraries(),

    // Tailwind @reference preloads and load paths, read from .info.yml.
    // Before tailwindcss(), which compiles the @reference rules it adds.
    drupalCss({ loadPaths, ...themes }),
    tailwindcss(),

    // SCSS compiled the way the Sass CLI did, partials preloaded the same way.
    drupalSass({ loadPaths, ...themes }),
  ],
  // ...build options as above.
});

Register what your sources actually need, which is a question about the language your stylesheets are written in rather than the framework you build with. Plain CSS goes through drupalCss, .scss through drupalSass, and a theme part-way through moving from one to the other registers both, each file handled by whichever matches its extension. Tailwind is not what decides it: it is a way of building, not a language, and it is just as usable from Sass. What drupalCss adds for it specifically is Tailwind’s @reference preloading, so a file can reach the theme’s utilities without emitting them a second time. drupalSass expects sass or sass-embedded installed alongside it, as any Sass build does.

Themes themselves need no naming here: a theme’s own files use the nearest theme that defines preloads, walking up the base theme: chain, so a subtheme inherits its parent’s without being told. Modules are the ones that need telling, because a module has no theme of its own — moduleTheme names the one it compiles against, and on a multisite siteThemes overrides that per site directory, so a module living under a site gets that site’s theme. What the preloading actually does, and how a file ends up with the right theme’s, is worth its own section further down.

Which raises a fair question: why does drupalSass exist at all, when Vite compiles .scss quite happily by itself? It does — but it compiles it Vite’s way, and existing Drupal SCSS was written for the Sass CLI’s. The difference that bites is url(). The CLI left those exactly as written, to be resolved against the compiled CSS; the plugin keeps that, so a partial pointing at ../images/icon.svg still means what it always meant instead of being taken over as a build asset and rewritten. (Vite resolves them from the entry file, which comes to the same thing as long as the entry and the old CSS output directory sit at the same depth — scss/style.scss to css/style.css.)

The rest is the same kind of accommodation: loadPaths standing in for --load-path, the webpack-style ~package/… prefix still accepted, relative @import and @use left to Sass itself to resolve, and the deprecation warnings that older code triggers on every single build silenced. The point is not that Vite gets Sass wrong. It is that a theme which has been compiling since the Sass CLI days carries on compiling, without first being converted to the module system.

drupalCss is not a compiler in that sense at all — it compiles nothing. It supplies the load paths for bare @import, and injects each file’s preloads as Tailwind @reference rules. That is why it is registered before tailwindcss() in the config above: the Tailwind plugin is what compiles the rules drupalCss has just added.

That is the whole of it for the simple case. The real configuration on a site with more going on gains options rather than entries — librariesDir to put contrib’s copies where contrib expects them, a CKEditor 5 plugin alongside, output naming so built files land under the module or theme they came from — but the library list is never one of them. That stays in the YAML, where Drupal already keeps it.

Two other files feed the same scan. A module’s or a theme’s .info.yml can carry a vite: key of its own, setting policy for everything in it rather than one library at a time. enableInAllLibraries means every library in that module or theme is managed without annotating each one; enableInAllComponents does the same for single-directory components. It is the difference between opting in per library and opting in once.

A theme’s .info.yml goes further, because some of this only makes sense for a theme: which stylesheet to read Tailwind’s or Bootstrap’s breakpoints from when generating *.breakpoints.yml, which Sass partials to preload, and the ckeditor5-stylesheets below. A theme’s might read:

vite:
  enableInAllLibraries: true
  breakpoints:
    css: scss/bootstrap.scss

A theme’s ckeditor5-stylesheets can be built the same way, so the styles the editor shows an author come from the same compiled source as the front end rather than a separately maintained file that drifts out of step with it. That one is off by default and has to be asked for, with ckeditor5Stylesheets: true on the plugin (vite-plugin-drupal-libraries 0.4.0 or later — on an older version the option is simply ignored), because on its own it only gets you half way. The build will happily compile the stylesheet, but ckeditor5-stylesheets is an .info.yml key rather than a library, and drupal/vite rewrites libraries — so without a patch it never swaps the declared path for the built one, and CKEditor goes on loading the uncompiled source while the compiled file sits there unused. The patch, #3447335, teaches it to rewrite those too, and is still open.

Defaulting the option off is the right way round. An option that quietly does nothing useful unless you have also applied a patch is worse than one you had to go looking for and read about first.

Both halves are small. The theme names the stylesheet it wants the editor to use, as it always did:

ckeditor5-stylesheets:
  - scss/ckeditor5.scss

and the plugin is told to treat it as a build entry:

drupalLibraries({
  ckeditor5Stylesheets: true,
}),

Note the theme is pointing at .scss. That is the whole appeal: the editor’s stylesheet is written in the same language, with the same variables and partials, as the theme it is meant to mirror — rather than being a hand-kept CSS file that slowly stops resembling the site.

It is also the moment to say what belongs in that file, because pointing ckeditor5-stylesheets at the whole of style.css is the usual mistake and it usually breaks the editor. Every rule in that file applies inside the editing area: the page grid, the header and navigation, resets, anything sized or positioned against the viewport. CKEditor renders authored content inside its own chrome, so site-level layout lands on the editor’s interface rather than politely under the content, and the editing surface comes out somewhere between subtly and spectacularly wrong.

The fix is to split the stylesheet so the content styles can be pulled out on their own — which is a split worth having regardless. Keep typography, lists, tables, blockquotes, figures and inline elements in their own partials, and keep layout, chrome and page furniture in others. Each entry point then imports only what it needs:

// scss/style.scss — the front end: all of it.
@use 'base/typography';
@use 'base/tables';
@use 'components/media';
@use 'layout/grid';
@use 'layout/header';
@use 'layout/navigation';

// scss/ckeditor5.scss — the editor: content styles only.
@use 'base/typography';
@use 'base/tables';
@use 'components/media';

Note that neither entry point imports the variables, and neither has to. Those arrive through the theme’s preload, described below — the compiler is handed the theme’s variables, functions and mixins before it reads either file, so the editor stylesheet can use them as freely as the front-end one does. It matters more here than anywhere else: an editor stylesheet assembled from a few content partials would otherwise be exactly the file most likely to reference a variable it forgot to import, and preloading removes that failure mode entirely. Because preloading emits nothing on its own, carrying the full set into a file this small costs nothing either.

A CSS-only theme does the same thing with @import and the plugin bundles it identically; the structure is what matters, not the syntax. Either way the editor now shows the same headings, the same table borders and the same blockquote treatment as the published page, compiled from the same partials against the same variables — and none of the furniture that means nothing inside a text field. Change the typography once and both move, because there is only one copy of it. That is the version of WYSIWYG worth having: not a stylesheet that resembles the site, but the site’s own content styles with the page around them left out.

That is the .info.yml side of it. Back to the library declarations themselves — because not every package needs one, and it is worth being clear about which do. A declaration is for packages whose files are served to the browser as they are — Leaflet, PhotoSwipe, a date library. Plenty of what you install is never served: it is consumed by the build and disappears into your own output.

Tailwind is the obvious case. You install it and @import it from your own stylesheet; the build compiles it in. There is no Tailwind library and nothing of Tailwind’s is copied into web/libraries — the package is consumed by the build and never appears again.

Your own stylesheet, though, is still declared, and declared the same way as everything else:

global:
  vite: true
  css:
    theme:
      css/style.css: {}

The path points at the source — the file you actually edit, the one whose first line is @import "tailwindcss". Vite compiles it, and drupal/vite swaps in the built, hashed result through the manifest when the page is rendered. The same applies to a Sass file, or a JavaScript entry that imports half of npm and bundles it.

So the mechanism never actually changes: a library with vite: true and a path. What differs is only where the path points — into node_modules for a package you want shipped as it is, or at your own source for something the build is going to compile. In both cases Drupal is told, in the same file in the same way, which assets the site needs.

The rule is simple enough, then: declare a package when you want its files shipped intact; install it and forget it when you only want its output. Both live in the same package.json and the same lock file either way, so npm audit covers the build toolchain and the served libraries alike — which is more than any of the three traditional approaches manage for either.

Versions come from the lock file, not from you

The detail that makes this worth doing is that the version is never typed by a human. Libraries loading a file from node_modules deliberately carry no version: key; a hook_library_info_alter() implementation reads the installed version out of package-lock.json and sets it.

Drupal then uses that version for its ?v= cache-busting query, so upgrading a package and rebuilding updates the URLs automatically. More importantly, the version in the lock file, the version in the copied directory name, and the version Drupal reports are all the same value from the same source. There is no drift, because there is nowhere for drift to happen.

That is the whole security argument in one sentence: because package-lock.json is the record of what is installed, npm audit is a true statement about what the site is serving.

It also closes the duplication problem from earlier, and closes it loudly. There is one node_modules for the whole project, so a package exists once no matter how many modules and themes declare libraries against it. If two libraries do somehow ask for the same package at different versions, the build stops and says so — at build time, on someone’s machine, rather than as a mystery on the one production page that loads both.

Contrib modules work unchanged

The obvious objection is contrib. Modules like magnific_popup and photoswipe expect to load from /libraries/<package>/, where Composer or a manual download would have put things. They cannot be expected to know about any of this.

They do not have to. With librariesDir: 'web/libraries' set, any library asset path of the form /libraries/<package>/<file> — in any module or theme, whether or not Vite manages that library — is copied unchanged from node_modules/<package>/<file> to exactly where the module looks for it. Installing the npm package of the same name is the entire installation procedure:

npm install -D [email protected] [email protected]
npm run build && drush cr

It is worth being clear about what triggers that, because it is not the mechanism described earlier. Your own libraries opt in explicitly: vite: true, and a path that points into node_modules. A contrib library has neither. It declares its assets the way it always has — an ordinary enabled library, no vite: key anywhere, and a path pointing at /libraries, because a module that knows nothing about Vite is never going to write one. The plugin reads the asset paths of every library it finds, managed or not, and when one has the shape /libraries/<package>/<file> it simply checks whether node_modules/<package>/<file> exists. If it does, that is taken as the same file and copied. If it does not, nothing happens and the library is left exactly as written.

Which makes installing the npm package the opt-in. drupal/photoswipe asks for /libraries/photoswipe/dist/umd/photoswipe.umd.min.js; the photoswipe package happens to carry a file at that same path, so once it is installed the two line up and the copy appears where the module expects it. Leave the package uninstalled and the module behaves exactly as it always has, looking in /libraries and finding whatever you put there by hand. There is no flag to set and nothing in contrib to change, which is the only reason this works on modules whose maintainers will never hear about any of it.

From Drupal’s side nothing is unusual. The module loads its files as it always did, they run as plain classic scripts, and the status report says “Installed”. The difference is invisible at runtime and total at maintenance time: those libraries are now in the lock file, and npm audit sees them.

That covers the common case, and it is worth saying where it stops. The trick works because the file can be served exactly as the module already expects it: a classic script at a path the npm package happens to share. When the file has to be processed before it is any use, copying it unchanged is not enough.

CKEditor 5 plugins are the case I hit. A plugin is an ES module that has to be built into something the editor can load, so a raw copy into /libraries is useless — it needs to go through the build and come out of the manifest instead. Those packages are named in librariesDirExclude so they are not copied across, and then something has to tell the contrib module to use the built version:

function mysite_elements_path_library_info_alter(array &$libraries, string $extension): void {
  if ($extension === 'ckeditor5_elements_path' && isset($libraries['elements_path'])) {
    // Load our built copy in place of the /libraries files.
    $libraries['elements_path']['js'] = [];
    $libraries['elements_path']['css'] = [];
    $libraries['elements_path']['dependencies'][] = 'mysite_elements_path/elements_path';
  }
}

So the honest version of “contrib works unchanged” is narrower than it first sounds. Contrib modules that want a prebuilt file from /libraries need nothing at all, which is most of them. Contrib modules whose asset has to be compiled first need a small site module holding a hook_library_info_alter() like the above, pointing the library at your own built one. That is a handful of lines rather than a patch, and it lives in your site rather than in somebody else’s module — but it is a shim, and pretending otherwise would be overselling it.

Each generated folder carries a .npm-libraries.json marker recording the package, version and files it owns. Only marked folders are replaced on rebuild, and they are removed when nothing references the package any more. A folder someone installed with Composer or by hand is left alone with a warning — so this can be adopted gradually, on a site that already has a populated /libraries, without a migration step.

The awkward cases are the interesting ones

Most of the work was not the happy path. It was the packages that do not fit the assumption that a file can simply be copied and loaded.

drupal/vite loads every rewritten script as type="module", which changes the rules. A UMD or IIFE bundle that expects to run with this set to window, and to leave a global behind, does neither inside a module. Those get global: true, which wraps the file so it behaves as it expects, and global: Name where a specific top-level binding needs re-exposing. ES modules such as countup.js take namespace: instead, keeping their named exports and attaching them to a chosen global.

Then there are packages that load their own files at runtime — Leaflet’s marker images, a date library’s locales, an editor’s skins. Those need copy: patterns, and the copies keep their path inside the package so that relative URLs continue to resolve. Images and fonts referenced from copied CSS via url() or @import are handled without any configuration, since the CSS is scanned and its references followed.

The packages with no browser-ready build — the ones that stop the Composer approach dead — turn out to need the least ceremony here, because a build step is already in the pipeline. Instead of pointing a library at a file inside the package, you write a small entry that imports from it and let Vite resolve and bundle the result. Bare specifiers resolve, because that is a bundler’s whole job. The same goes for stylesheets: a package shipping SCSS rather than CSS becomes an entry that imports the SCSS, compiled through the same pipeline as your own.

The case I enjoyed most was Bootstrap 4.6.2, which is precisely that — one entry importing Bootstrap’s SCSS behind your own variable overrides, another importing its JavaScript together with jQuery 3 and Popper. Its JavaScript refuses to run against jQuery 4, and Drupal 11 ships jQuery 4.0.0. Bundled as ES modules, jQuery 3 and Bootstrap set no globals at all, so Drupal’s window.jQuery remains 4.0.0 while Bootstrap quietly uses its own private copy. The data API keeps working; code that needs the plugins reaches for an explicitly exposed binding rather than Drupal’s jQuery. Two versions of jQuery on one page, neither aware of the other, and nothing to configure in Drupal.

One build, not several

Everything so far has been about packages, which undersells the thing doing the work. Vite is a compiler, not a file-copier, and once a Drupal site has a real build in it, several problems that are usually solved separately stop being separate problems.

Stylesheets are the easy example. Sass compiles, and so does whatever modern CSS you fancy — nesting, custom media, the syntax that is still a year away from being safe to ship — because the build is what decides what the browser receives. That is ordinary for a front-end developer and unusual for a Drupal theme, which is rather the point.

Being able to write the syntax is only half of what that buys, and the quieter half is the more useful one: the build knows which browsers you support, and holds the output to it. A browserslist query states that floor once, in one place, and everything downstream obeys it — vendor prefixes generated where those browsers still need them and left out where they do not, newer syntax lowered into something they understand, and the question of whether a rule works in the oldest browser you claim to support answered mechanically rather than by hoping. Raise the floor when you decide to raise it, and the next build changes the output to match.

Hand-maintained CSS in a theme has none of that. The prefixes in it are whatever somebody pasted from a blog post several years ago: still there long after the browsers that needed them are gone, and missing for the ones that have arrived since. Nothing anywhere states which browsers the theme is meant to support, so nothing can check that it does, and the answer arrives from a user on a device nobody tested.

Breakpoints are a smaller example of the same idea, and a nice one because the duplication is so familiar. Drupal keeps its own <theme>.breakpoints.yml, which responsive images and anything else breakpoint-aware read from. Your CSS framework already knows its breakpoints — Tailwind’s --breakpoint-*, Bootstrap’s $grid-breakpoints — and the moment you are building on one of those, its values are the real ones. They are what the browser actually lays the page out by. Drupal’s file is a second-hand copy, which makes this less a duplication between equals than a one-way dependency: the framework leads and Drupal follows, permanently a step behind.

Without a build the two are kept in step by hand, and when they drift it is not symmetrical — it is Drupal’s copy that is simply wrong. Retune a breakpoint in the theme, or take a framework upgrade that shifts one, and nothing anywhere says the YAML now describes a layout that no longer exists. It surfaces later, as a responsive image choosing a different size from the layout around it.

So let the build settle it. It can read the resolved values straight out of the compiled stylesheet and write the YAML from them, which puts the relationship the right way round: Tailwind or Bootstrap becomes the source of truth for breakpoints — the one place a value is ever authored — and <theme>.breakpoints.yml becomes a generated artefact that follows it, exactly as the compiled CSS does. Drupal still gets its file, and responsive images still work; it simply stops being something anyone maintains:

# Generated from css/style.css (Tailwind's --breakpoint-* theme variables).
hc_theme.sm:
  label: sm
  mediaQuery: 'all and (min-width: 640px)'
  weight: 0
  multipliers:
    - 1x

There is a plugin per framework, registered beside the others, and the theme opts in with the breakpoints: key shown earlier — naming the stylesheet to read them from, and optionally a prefix and the multipliers every breakpoint should get:

import tailwindBreakpoints from 'vite-plugin-drupal-tailwind-breakpoints';
// …or, for a Bootstrap theme:
// import bootstrapBreakpoints from 'vite-plugin-drupal-bootstrap-breakpoints';

plugins: [
  // …
  tailwindBreakpoints(),
],

Two plugins rather than one, because the two frameworks keep their breakpoints somewhere quite different. Bootstrap compiles $grid-breakpoints out as custom properties — --breakpoint-sm in Bootstrap 4, --bs-breakpoint-* in 5.3 — so that plugin compiles the stylesheet through Vite’s CSS pipeline, preloaded variables and all, and reads the values off :root. Tailwind never emits its breakpoints at all: it compiles them directly into media queries, so there is nothing in the output to read back. That plugin resolves the stylesheet’s theme with Tailwind’s own loader instead and takes --breakpoint-* from there, which has the pleasant side effect of seeing both Tailwind’s defaults and whatever the theme overrides in @theme. Same file out of both, and in neither case is a breakpoint written down twice: the framework holds it, Drupal is handed a copy.

One caveat, because it is the kind that costs an afternoon: Drupal caches breakpoints. The file is rewritten on every build and dev-server start, and again in dev when a stylesheet it depends on changes — but only when the contents actually differ — and Drupal carries on using the old values until drush cr.

Change a breakpoint in the theme and rebuild, and Drupal’s idea of it changes with it. Take a framework upgrade that moves one of its own, and the same thing happens — without anyone having to notice it moved, which is the case that would otherwise go unnoticed longest. There is no second place to remember.

Preloading is the option I would miss most, and it solves something every themer has quietly put up with. A component’s stylesheet needs the theme’s variables, or its Tailwind utilities, so every file opens with the same two or three lines of ceremony before any actual styling starts. Worse, a module’s CSS usually cannot reach them at all, so module styling ends up either hardcoding values or giving up and living in the theme.

Instead, a theme says once what every file should already have:

# Tailwind: added to each file as @reference, so it emits no CSS of its own.
vite:
  preload: [css/style.css]

or, for Sass, in the three groups it actually matters for:

vite:
  preload:
    functions: [bootstrap/scss/functions]
    variables: [scss/_variables.scss]
    mixins: [scss/_mixins.scss]

The thing that makes this safe to do to every file is that it generates nothing. Preloading hands the compiler the variables, functions, mixins and utilities so they are in scope — it does not emit them. Tailwind preloads arrive as @reference, which produces no CSS; Sass preloads are definitions, which produce no CSS either. You get the theme’s vocabulary available in every file and not one extra byte in the output. The corollary is that a preloaded file must contain only definitions: put an actual rule in one and it really will be emitted into every compiled file.

They are loaded with @use ... as *, so they work in files that already start with @use, and the ordering is worth noticing: functions come theme-then-module, mixins the same, but variables come module-then-theme, so a module’s values land before the theme’s !defaults and therefore win.

Which theme’s preloads a given file gets is the interesting bit on a real site. A theme’s own files use the nearest theme with preload, walking up the base theme: chain, so a subtheme inherits its parent’s. Files in modules get a theme’s and then their own — which theme being the point of moduleTheme:

drupalCss({
  loadPaths: ['node_modules', 'web/themes/custom'],
  // Modules get this theme's preloads, so their CSS can use its utilities.
  moduleTheme: 'my_theme',
}),

And on a multisite, a module living in a site’s own sites/<site>/modules gets that site’s theme instead, which is what siteThemes is for — keys are site directory names, and globs are allowed:

drupalSass({
  loadPaths: ['node_modules', 'web/themes/custom'],
  moduleTheme: 'base_theme',
  siteThemes: {
    'site-a': 'site_a_theme',
    'site-b': 'site_b_theme',
  },
}),

Both plugins take both options and resolve themes identically — the two examples above split them only to avoid printing the same thing twice. So shared modules compile against the shared theme, a site’s own modules compile against that site’s, and neither needs to know which it is. Anything that wants none of it says vite: { preload: false } and is left alone.

The one I did not expect to care about is CKEditor 5. Writing a plugin for it officially means webpack: its own config, its own conventions, its own build, sitting alongside whatever the theme already uses. Vite can produce the same thing from the same sources, in Drupal’s own js/ckeditor5_plugins/ layout, resolving ckeditor5/src/* against the DLL core already loads. The webpack install goes away.

That one is vite-plugin-drupal-ckeditor5, registered like the rest:

import ckeditor5Plugins from 'vite-plugin-drupal-ckeditor5';

plugins: [
  // …
  ckeditor5Plugins(),
],

The sources do not move and do not change. They stay in <module>/js/ckeditor5_plugins/<pluginName>/src/ where Drupal already expects them, written exactly as they were for webpack. import { Plugin } from 'ckeditor5/src/core' becomes a lookup in the CKEditor 5 DLL that core already loads, so the plugin shares core’s CKEditor rather than bundling a second copy of it. import icon from './icon.svg' hands back the SVG markup, as webpack’s raw-loader did. The default export of src/index.js is registered as CKEditor5.<pluginName>, which is precisely where Drupal goes looking based on the *.ckeditor5.yml. Which plugins to build is read from that same file — so, as everywhere else here, there is no list to keep.

One thing does run backwards here, and it is worth flagging because it inverts the rule everywhere else in this article. Normally a library points at the source and drupal/vite substitutes the built file through the manifest. A CKEditor 5 plugin cannot start that way: the *.ckeditor5.yml and the library it names both declare js/build/<pluginName>.js — the built path — because that is the convention the webpack and DLL build established, and it is where Drupal still goes looking.

So the module swaps it the other way round. A hook_library_info_alter() replaces that built path with the plugin’s source and sets vite: true on the library, running before drupal/vite’s own hook; from there everything proceeds as usual, with drupal/vite rewriting the source to the Vite build, or to the dev server while you are working. The declaration still ends up pointing at the source, as everywhere else. It just takes a hook to get it there, rather than being written that way in the first place.

Which is the same shape as the contrib shim earlier, and the two are worth recognising as one pattern rather than two unrelated quirks. In both, Drupal is looking for a finished file at a path fixed by convention, and in both a few lines of hook_library_info_alter() in a site module are what redirect it at the build instead. Only the reach differs, and it differs for a reason: a plugin of your own keeps its library and simply has the path rewritten to the source, because you own the module declaring it. A contrib plugin’s library has to be hollowed out instead — its js and css emptied and a dependency on one of yours added — precisely because you do not.

Neither is elegant, and I would not claim otherwise. But both are a handful of lines in a file you control, which is the trade this whole approach keeps making: a small shim you own, in preference to a patch you have to carry against somebody else’s module and reapply on every update.

The opt-out matters more than it looks, given everything said earlier about contrib. A plugin whose library carries vite: false is skipped entirely, so a contrib module shipping its own webpack build keeps it, on a site where everything else is built by Vite. The two coexist, rather than one of them having to win first.

The same pipeline will build a React component, which is where this stops being only about stylesheets. Drupal sites regularly need one genuinely interactive thing — a calculator, a filtered map, a booking widget — and the usual answers are both bad: write it in jQuery because that is what the theme has, or decouple the whole site to justify a front-end framework for one widget.

With a build already present, neither is necessary. Add the React plugin, and a component declares a .jsx entry the same way any other library declares a file. On one site I have a salary-sacrifice calculator as a single-directory component:

name: Calculator
props:
  type: object
  properties:
    title:
      type: string
      title: Calculator heading
libraryOverrides:
  js:
    js/calculator.jsx: {}
  dependencies:
    - core/drupal
    - core/once

From Drupal’s side that is an ordinary component: it takes props, it is placed in a layout or a template like any other, and its settings arrive through drupalSettings. From the front end’s side it is an ordinary React entry point, with Fast Refresh while the dev server is running. The build bundles it, Drupal attaches it on the pages that use it, and nothing about the rest of the site changes — islands of React in a perfectly normal Drupal page, rather than an architecture decision imposed on everything.

There is a habit worth breaking here too. A front-end build usually implies a bundle — everything concatenated, shipped on every page, and the size problem solved later with code splitting and a router. Drupal has never needed that. It has had a dependency-aware library system for years, which already knows that this page rendered a card and a hero and therefore wants those two stylesheets and nothing else.

So the build does not have to fight it. Rather than one output, it can produce one file per library and let Drupal keep doing what it already does. This site’s theme builds fifteen separate stylesheets from fifteen library declarations, each attached by the component that uses it: the global sheet is 33 kB, but the card component is 2.8 kB and the hero 4.9 kB, and a page gets the ones it actually rendered.

That is an unusual position to be in. Most build setups have to reinvent dependency tracking to work out what a page needs; here it was already there, in the same declaration that says where the file comes from. The build and the library system are answering two halves of one question — what is this file, and who needs it — instead of each having its own opinion.

Which leaves one build for the site. The theme’s CSS, a module’s JavaScript, an npm library copied in untouched, the editor’s stylesheet, a CKEditor plugin — one command, one config, one lock file, one set of conventions to learn. Not four tools that each half-know about Drupal, which is roughly where a site ends up if each of those problems is solved on its own terms as it arrives.

Was it worth it?

It has stopped being a question I am asking. This runs on my own sites and on a number of client ones, through ordinary deployments, and the plugins are on npm rather than in a branch somewhere. It is not a contrib module you enable and forget — it needs drupal/vite, a couple of Vite plugins, a build step in your deployment, and the CKEditor 5 stylesheet piece still wants a patch. But the uncertainty is gone: the awkward cases above are awkward cases I have already hit and worked through, not ones I am anticipating.

What it demonstrates is that the gap is not inherent to Drupal. The asset layer is already declarative: *.libraries.yml is a perfectly good manifest, and it is the one place assets are listed. Pointing those declarations at node_modules rather than at committed files or CDN URLs is enough to inherit everything npm already provides — exact versions, a lock file, a dependency graph, and an advisory database that tooling already understands.

The front end stops being the part of the site nobody can answer questions about. That seems worth the trouble.

Whether any of this ends up mattering in core depends on work happening elsewhere. If something like nod_’s PHP-npm prototype makes acquisition work without Node.js, the in-UI install case is covered too, and the remaining question is the one this approach answers: what decides which files reach the page, and at which version. I think the answer is already sitting in every module and theme in the project, in a file we have been writing all along.

None of which, in the end, is really about Vite. The front-end developers who already do this well are not waiting on any of it. What is missing is only that the rest of us can follow them without leaving Drupal’s own asset layer behind.

And if nothing comes of it, the nine-year-old issue is still open. Comment one hundred and thirty-one is available.