Skip to content

Commit

Permalink
feat(lucide-react): Add DynamicIcon component (#2686)
Browse files Browse the repository at this point in the history
* Adding the DynamicIcon component

* Fix imports

* Add docs

* Formatting

* Fix use client in output rollup

* revert changes

* Fix formatting

* Revert changes in icons directory

* Revert time command

* update exports
  • Loading branch information
ericfennis authored Jan 10, 2025
1 parent d5fe5a0 commit 58c2e10
Show file tree
Hide file tree
Showing 11 changed files with 281 additions and 110 deletions.
105 changes: 9 additions & 96 deletions docs/guide/packages/lucide-react.md
Original file line number Diff line number Diff line change
Expand Up @@ -85,108 +85,21 @@ const App = () => (
);
```

## One generic icon component
## Dynamic Icon Component

It is possible to create one generic icon component to load icons, but it is not recommended.
Since it is importing all icons during build. This increases build time and the different modules it will create.

::: danger
The example below imports all ES Modules, so exercise caution when using it. Importing all icons will significantly increase the build size of the application, negatively affecting its performance. This is especially important to keep in mind when using bundlers like `Webpack`, `Rollup`, or `Vite`.
`DynamicIcon` is useful for applications that want to show icons dynamically by icon name. For example, when using a content management system with where icon names are stored in a database.

This is not the case for the latest NextJS, because it uses server side rendering. The icons will be streamed to the client when needed. For NextJS with Dynamic Imports, see [dynamic imports](#nextjs-example) section for more information.
:::
For static use cases, it is recommended to import the icons directly.

### Icon Component Example
The same props can be passed to adjust the icon appearance. The `name` prop is required to load the correct icon.

```jsx
import { icons } from 'lucide-react';

const Icon = ({ name, color, size }) => {
const LucideIcon = icons[name];

return <LucideIcon color={color} size={size} />;
};

export default Icon;
```

#### Using the Icon Component

```jsx
import Icon from './Icon';

const App = () => {
return <Icon name="Home" />;
};

export default App;
```

#### With Dynamic Imports

Lucide react exports a dynamic import map `dynamicIconImports`, which is useful for applications that want to show icons dynamically by icon name. For example, when using a content management system with where icon names are stored in a database.

When using client side rendering, it will fetch the icon component when it's needed. This will reduce the initial bundle size.

The keys of the dynamic import map are the lucide original icon names (kebab case).

Example with React suspense:

```tsx
import React, { lazy, Suspense } from 'react';
import { LucideProps } from 'lucide-react';
import dynamicIconImports from 'lucide-react/dynamicIconImports';
import { DynamicIcon } from 'lucide-react/dynamic';

const fallback = <div style={{ background: '#ddd', width: 24, height: 24 }}/>

interface IconProps extends Omit<LucideProps, 'ref'> {
name: keyof typeof dynamicIconImports;
}

const Icon = ({ name, ...props }: IconProps) => {
const LucideIcon = lazy(dynamicIconImports[name]);

return (
<Suspense fallback={fallback}>
<LucideIcon {...props} />
</Suspense>
);
}

export default Icon
```

##### NextJS Example

In NextJS, [the dynamic function](https://nextjs.org/docs/pages/building-your-application/optimizing/lazy-loading#nextdynamic) can be used to dynamically load the icon component.

To make dynamic imports work with NextJS, you need to add `lucide-react` to the [`transpilePackages`](https://nextjs.org/docs/app/api-reference/next-config-js/transpilePackages) option in your `next.config.js` like this:

```js
/** @type {import('next').NextConfig} */
const nextConfig = {
transpilePackages: ['lucide-react'] // add this
}

module.exports = nextConfig

```

You can then start using it:

```tsx
import dynamic from 'next/dynamic'
import { LucideProps } from 'lucide-react';
import dynamicIconImports from 'lucide-react/dynamicIconImports';

interface IconProps extends LucideProps {
name: keyof typeof dynamicIconImports;
}

const Icon = ({ name, ...props }: IconProps) => {
const LucideIcon = dynamic(dynamicIconImports[name])

return <LucideIcon {...props} />;
};

export default Icon;
const App = () => (
<DynamicIcon name="camera" color="red" size={48} />
);
```
52 changes: 44 additions & 8 deletions packages/lucide-react/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -23,18 +23,53 @@
],
"author": "Eric Fennis",
"amdName": "lucide-react",
"source": "src/lucide-react.ts",
"main": "dist/cjs/lucide-react.js",
"main:umd": "dist/umd/lucide-react.js",
"module": "dist/esm/lucide-react.js",
"unpkg": "dist/umd/lucide-react.min.js",
"typings": "dist/lucide-react.d.ts",
"sideEffects": false,
"types": "dist/lucide-react.d.ts",
"files": [
"dist",
"dynamicIconImports.js",
"dynamicIconImports.js.map",
"dynamicIconImports.d.ts"
"dist"
],
"exports": {
".": {
"types": "./dist/lucide-react.d.ts",
"import": "./dist/esm/lucide-react.js",
"browser": "./dist/esm/lucide-react.js",
"require": "./dist/cjs/lucide-react.js",
"node": "./dist/cjs/lucide-react.js"
},
"./icons": {
"types": "./dist/lucide-react.d.ts",
"import": "./dist/esm/lucide-react.js",
"browser": "./dist/esm/lucide-react.js",
"require": "./dist/cjs/lucide-react.js",
"node": "./dist/cjs/lucide-react.js"
},
"./icons/*": {
"types": "./dist/icons/*.d.ts",
"import": "./dist/esm/icons/*.js",
"browser": "./dist/esm/icons/*.js",
"require": "./dist/cjs/icons/*.js",
"node": "./dist/cjs/icons/*.js"
},
"./dynamic": {
"types": "./dist/dynamic.d.ts",
"import": "./dist/esm/dynamic.js",
"browser": "./dist/esm/dynamic.js",
"require": "./dist/cjs/dynamic.js",
"node": "./dist/cjs/dynamic.js"
},
"./dynamicIconImports": {
"types": "./dist/dynamicIconImports.d.ts",
"import": "./dist/esm/dynamicIconImports.js",
"browser": "./dist/esm/dynamicIconImports.js",
"require": "./dist/cjs/dynamicIconImports.js",
"node": "./dist/cjs/dynamicIconImports.js"
},
"./src/*": "./src/*.ts",
"./package.json": "./package.json"
},
"sideEffects": false,
"scripts": {
"build": "pnpm clean && pnpm copy:license && pnpm build:icons && pnpm typecheck && pnpm build:bundles",
"copy:license": "cp ../../LICENSE ./LICENSE",
Expand All @@ -60,6 +95,7 @@
"react-dom": "18.2.0",
"rollup": "^4.22.4",
"rollup-plugin-dts": "^6.1.0",
"rollup-plugin-preserve-directives": "^0.4.0",
"typescript": "^4.9.5",
"vite": "5.1.8",
"vitest": "^1.1.1"
Expand Down
43 changes: 38 additions & 5 deletions packages/lucide-react/rollup.config.mjs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import plugins from '@lucide/rollup-plugins';
import preserveDirectives from 'rollup-plugin-preserve-directives';
import pkg from './package.json' assert { type: 'json' };
import dts from 'rollup-plugin-dts';
import getAliasesEntryNames from './scripts/getAliasesEntryNames.mjs';
Expand Down Expand Up @@ -34,14 +35,15 @@ const bundles = [
},
{
format: 'esm',
inputs: ['src/dynamicIconImports.ts'],
outputFile: 'dynamicIconImports.js',
inputs: ['src/dynamic.ts', 'src/dynamicIconImports.ts', 'src/DynamicIcon.ts'],
outputDir,
preserveModules: true,
external: [/src/],
paths: (id) => {
if (id.match(/src/)) {
const [, modulePath] = id.match(/src\/(.*)\.ts/);

return `dist/esm/${modulePath}.js`;
return `${modulePath}.js`;
}
},
},
Expand All @@ -62,7 +64,14 @@ const configs = bundles
}) =>
inputs.map((input) => ({
input,
plugins: plugins({ pkg, minify }),
plugins: [
...plugins({ pkg, minify }),
// Make sure we emit "use client" directive to make it compatible with Next.js
preserveDirectives({
include: 'src/DynamicIcon.ts',
suppressPreserveModulesWarning: true,
}),
],
external: ['react', 'prop-types', ...external],
output: {
name: packageName,
Expand Down Expand Up @@ -95,7 +104,31 @@ export default [
input: 'src/dynamicIconImports.ts',
output: [
{
file: `dynamicIconImports.d.ts`,
file: `dist/dynamicIconImports.d.ts`,
format: 'es',
},
],
plugins: [
dts({
exclude: ['./src/icons'],
}),
],
},
{
input: 'src/dynamic.ts',
output: [
{
file: `dist/dynamic.d.ts`,
format: 'es',
},
],
plugins: [dts()],
},
{
input: 'src/DynamicIcon.ts',
output: [
{
file: `dist/DynamicIcon.d.ts`,
format: 'es',
},
],
Expand Down
5 changes: 4 additions & 1 deletion packages/lucide-react/scripts/exportTemplate.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,9 @@ export default ({ componentName, iconName, children, getSvg, deprecated, depreca

return `
import createLucideIcon from '../createLucideIcon';
import { IconNode } from '../types';
export const __iconNode: IconNode = ${JSON.stringify(children)}
/**
* @component @name ${componentName}
Expand All @@ -19,7 +22,7 @@ import createLucideIcon from '../createLucideIcon';
* @returns {JSX.Element} JSX Element
* ${deprecated ? `@deprecated ${deprecationReason}` : ''}
*/
const ${componentName} = createLucideIcon('${componentName}', ${JSON.stringify(children)});
const ${componentName} = createLucideIcon('${componentName}', __iconNode);
export default ${componentName};
`;
Expand Down
73 changes: 73 additions & 0 deletions packages/lucide-react/src/DynamicIcon.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
'use client';

import { createElement, forwardRef, useEffect, useState } from 'react';
import { IconNode, LucideIcon, LucideProps } from './types';
import dynamicIconImports from './dynamicIconImports';
import Icon from './Icon';

export type DynamicIconModule = { default: LucideIcon; __iconNode: IconNode };

export type IconName = keyof typeof dynamicIconImports;

export const iconNames = Object.keys(dynamicIconImports) as Array<IconName>;

interface DynamicIconComponentProps extends LucideProps {
name: IconName;
fallback?: () => JSX.Element | null;
}

async function getIconNode(name: IconName) {
if (!(name in dynamicIconImports)) {
throw new Error('[lucide-react]: Name in Lucide DynamicIcon not found');
}

// TODO: Replace this with a generic iconNode package.
const icon = (await dynamicIconImports[name]()) as DynamicIconModule;

return icon.__iconNode;
}

/**
* Dynamic Lucide icon component
*
* @component Icon
* @param {object} props
* @param {string} props.color - The color of the icon
* @param {number} props.size - The size of the icon
* @param {number} props.strokeWidth - The stroke width of the icon
* @param {boolean} props.absoluteStrokeWidth - Whether to use absolute stroke width
* @param {string} props.className - The class name of the icon
* @param {IconNode} props.children - The children of the icon
* @param {IconNode} props.iconNode - The icon node of the icon
*
* @returns {ForwardRefExoticComponent} LucideIcon
*/
const DynamicIcon = forwardRef<SVGSVGElement, DynamicIconComponentProps>(
({ name, fallback: Fallback, ...props }, ref) => {
const [iconNode, setIconNode] = useState<IconNode>();

useEffect(() => {
getIconNode(name)
.then(setIconNode)
.catch((error) => {
console.error(error);
});
}, [name]);

if (iconNode == null) {
if (Fallback == null) {
return null;
}

return createElement(Fallback);
}

return createElement(Icon, {
ref,
...props,
iconNode,
});
},
);

export default DynamicIcon;
7 changes: 7 additions & 0 deletions packages/lucide-react/src/dynamic.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
export {
default as DynamicIcon,
iconNames,
type DynamicIconModule,
type IconName,
} from './DynamicIcon';
export { default as dynamicIconImports } from './dynamicIconImports';
Loading

0 comments on commit 58c2e10

Please sign in to comment.