A Vite plugin to replace imports for Lucide icons.
If you want to import Lucide icons in your project, you can use two methods since
this PR on Lucide (at least for lucide-svelte
):
import { IconName } from "lucide-svelte";
// or
import IconName from "lucide-svelte/icons/icon-name";
While the first method is more convenient (and may be the one used by auto-import features in your editor),
it is not tree-shakable.
In fact, a single import from "lucide-<framework>"
will import all icons, not ideal for Vite dev
server performance and build time.
More information here.
This plugin will replace the first method with the second one, so you can keep the convenience of the first method while benefiting from tree-shaking optimizations. “Correct” imports will be kept as-is.
Note
The plugin is primarily intended for lucide-svelte
, but it should work with
any Lucide package using Vite if they follow the same structure.
I got the idea from Phosphor Icons' optimizer. However, this plugin is written from scratch and is not based on the Phosphor one (even though the technique is essentially the same).
As it is a Vite plugin and not a Svelte one, it is more generic and can be used with any framework.
Additionally, it doesn't suffer from the limitations of the Svelte plugin, preventing the Phosphor
optimizer from working without disabling the native Vite optimizations of phosphor-svelte
.
This should subjectively be a feature embedded in Lucide itself (lucide-svelte/preprocessor
),
but I don't know if it will ever be implemented.
I opened an issue on the lucide-icons
repository to discuss
this.
As of version 1.1.0, the plugin includes an auto-updater. It helps support the renamed and deprecated icons by automatically updating the plugin when necessary.
If you use a recently deprecated icon and can't make your build work, please wait for a few hours for the plugin to update itself. If the problem persists, please open an issue in this repository.
More information about the auto-updater can be found in #6.
Install the plugin with your package manager of choice:
pnpm i -D vite-plugin-lucide-preprocess
Then, add it to your vite.config.js
/.ts
:
import { defineConfig } from "vite";
import lucidePreprocess from "vite-plugin-lucide-preprocess";
export default defineConfig({
plugins: [lucidePreprocess(), ...]
});
Warning
Make sure to add the plugin before any other preprocessors in the plugins
array.
The plugin optionally accepts an object with the following options:
-
importMode
(default:"esm"
): The import mode for CommonJS-compatible frameworks."esm"
: Import the icons as ES modules."cjs"
: Import the icons as CommonJS modules.
This option is useful if you use a CommonJS-compatible framework like React or Vue. It will automatically replace the imports with the correct syntax depending on whether your framework supports CJS or not.
MIT