Skip to content

Commit 58c2e10

Browse files
authored
feat(lucide-react): Add DynamicIcon component (#2686)
* 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
1 parent d5fe5a0 commit 58c2e10

File tree

11 files changed

+281
-110
lines changed

11 files changed

+281
-110
lines changed

docs/guide/packages/lucide-react.md

Lines changed: 9 additions & 96 deletions
Original file line numberDiff line numberDiff line change
@@ -85,108 +85,21 @@ const App = () => (
8585
);
8686
```
8787

88-
## One generic icon component
88+
## Dynamic Icon Component
8989

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

92-
::: danger
93-
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`.
93+
`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.
9494

95-
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.
96-
:::
95+
For static use cases, it is recommended to import the icons directly.
9796

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

10099
```jsx
101-
import { icons } from 'lucide-react';
102-
103-
const Icon = ({ name, color, size }) => {
104-
const LucideIcon = icons[name];
105-
106-
return <LucideIcon color={color} size={size} />;
107-
};
108-
109-
export default Icon;
110-
```
111-
112-
#### Using the Icon Component
113-
114-
```jsx
115-
import Icon from './Icon';
116-
117-
const App = () => {
118-
return <Icon name="Home" />;
119-
};
120-
121-
export default App;
122-
```
123-
124-
#### With Dynamic Imports
125-
126-
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.
127-
128-
When using client side rendering, it will fetch the icon component when it's needed. This will reduce the initial bundle size.
129-
130-
The keys of the dynamic import map are the lucide original icon names (kebab case).
131-
132-
Example with React suspense:
133-
134-
```tsx
135-
import React, { lazy, Suspense } from 'react';
136-
import { LucideProps } from 'lucide-react';
137-
import dynamicIconImports from 'lucide-react/dynamicIconImports';
100+
import { DynamicIcon } from 'lucide-react/dynamic';
138101

139-
const fallback = <div style={{ background: '#ddd', width: 24, height: 24 }}/>
140-
141-
interface IconProps extends Omit<LucideProps, 'ref'> {
142-
name: keyof typeof dynamicIconImports;
143-
}
144-
145-
const Icon = ({ name, ...props }: IconProps) => {
146-
const LucideIcon = lazy(dynamicIconImports[name]);
147-
148-
return (
149-
<Suspense fallback={fallback}>
150-
<LucideIcon {...props} />
151-
</Suspense>
152-
);
153-
}
154-
155-
export default Icon
156-
```
157-
158-
##### NextJS Example
159-
160-
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.
161-
162-
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:
163-
164-
```js
165-
/** @type {import('next').NextConfig} */
166-
const nextConfig = {
167-
transpilePackages: ['lucide-react'] // add this
168-
}
169-
170-
module.exports = nextConfig
171-
172-
```
173-
174-
You can then start using it:
175-
176-
```tsx
177-
import dynamic from 'next/dynamic'
178-
import { LucideProps } from 'lucide-react';
179-
import dynamicIconImports from 'lucide-react/dynamicIconImports';
180-
181-
interface IconProps extends LucideProps {
182-
name: keyof typeof dynamicIconImports;
183-
}
184-
185-
const Icon = ({ name, ...props }: IconProps) => {
186-
const LucideIcon = dynamic(dynamicIconImports[name])
187-
188-
return <LucideIcon {...props} />;
189-
};
190-
191-
export default Icon;
102+
const App = () => (
103+
<DynamicIcon name="camera" color="red" size={48} />
104+
);
192105
```

packages/lucide-react/package.json

Lines changed: 44 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -23,18 +23,53 @@
2323
],
2424
"author": "Eric Fennis",
2525
"amdName": "lucide-react",
26+
"source": "src/lucide-react.ts",
2627
"main": "dist/cjs/lucide-react.js",
27-
"main:umd": "dist/umd/lucide-react.js",
2828
"module": "dist/esm/lucide-react.js",
29-
"unpkg": "dist/umd/lucide-react.min.js",
30-
"typings": "dist/lucide-react.d.ts",
31-
"sideEffects": false,
29+
"types": "dist/lucide-react.d.ts",
3230
"files": [
33-
"dist",
34-
"dynamicIconImports.js",
35-
"dynamicIconImports.js.map",
36-
"dynamicIconImports.d.ts"
31+
"dist"
3732
],
33+
"exports": {
34+
".": {
35+
"types": "./dist/lucide-react.d.ts",
36+
"import": "./dist/esm/lucide-react.js",
37+
"browser": "./dist/esm/lucide-react.js",
38+
"require": "./dist/cjs/lucide-react.js",
39+
"node": "./dist/cjs/lucide-react.js"
40+
},
41+
"./icons": {
42+
"types": "./dist/lucide-react.d.ts",
43+
"import": "./dist/esm/lucide-react.js",
44+
"browser": "./dist/esm/lucide-react.js",
45+
"require": "./dist/cjs/lucide-react.js",
46+
"node": "./dist/cjs/lucide-react.js"
47+
},
48+
"./icons/*": {
49+
"types": "./dist/icons/*.d.ts",
50+
"import": "./dist/esm/icons/*.js",
51+
"browser": "./dist/esm/icons/*.js",
52+
"require": "./dist/cjs/icons/*.js",
53+
"node": "./dist/cjs/icons/*.js"
54+
},
55+
"./dynamic": {
56+
"types": "./dist/dynamic.d.ts",
57+
"import": "./dist/esm/dynamic.js",
58+
"browser": "./dist/esm/dynamic.js",
59+
"require": "./dist/cjs/dynamic.js",
60+
"node": "./dist/cjs/dynamic.js"
61+
},
62+
"./dynamicIconImports": {
63+
"types": "./dist/dynamicIconImports.d.ts",
64+
"import": "./dist/esm/dynamicIconImports.js",
65+
"browser": "./dist/esm/dynamicIconImports.js",
66+
"require": "./dist/cjs/dynamicIconImports.js",
67+
"node": "./dist/cjs/dynamicIconImports.js"
68+
},
69+
"./src/*": "./src/*.ts",
70+
"./package.json": "./package.json"
71+
},
72+
"sideEffects": false,
3873
"scripts": {
3974
"build": "pnpm clean && pnpm copy:license && pnpm build:icons && pnpm typecheck && pnpm build:bundles",
4075
"copy:license": "cp ../../LICENSE ./LICENSE",
@@ -60,6 +95,7 @@
6095
"react-dom": "18.2.0",
6196
"rollup": "^4.22.4",
6297
"rollup-plugin-dts": "^6.1.0",
98+
"rollup-plugin-preserve-directives": "^0.4.0",
6399
"typescript": "^4.9.5",
64100
"vite": "5.1.8",
65101
"vitest": "^1.1.1"

packages/lucide-react/rollup.config.mjs

Lines changed: 38 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import plugins from '@lucide/rollup-plugins';
2+
import preserveDirectives from 'rollup-plugin-preserve-directives';
23
import pkg from './package.json' assert { type: 'json' };
34
import dts from 'rollup-plugin-dts';
45
import getAliasesEntryNames from './scripts/getAliasesEntryNames.mjs';
@@ -34,14 +35,15 @@ const bundles = [
3435
},
3536
{
3637
format: 'esm',
37-
inputs: ['src/dynamicIconImports.ts'],
38-
outputFile: 'dynamicIconImports.js',
38+
inputs: ['src/dynamic.ts', 'src/dynamicIconImports.ts', 'src/DynamicIcon.ts'],
39+
outputDir,
40+
preserveModules: true,
3941
external: [/src/],
4042
paths: (id) => {
4143
if (id.match(/src/)) {
4244
const [, modulePath] = id.match(/src\/(.*)\.ts/);
4345

44-
return `dist/esm/${modulePath}.js`;
46+
return `${modulePath}.js`;
4547
}
4648
},
4749
},
@@ -62,7 +64,14 @@ const configs = bundles
6264
}) =>
6365
inputs.map((input) => ({
6466
input,
65-
plugins: plugins({ pkg, minify }),
67+
plugins: [
68+
...plugins({ pkg, minify }),
69+
// Make sure we emit "use client" directive to make it compatible with Next.js
70+
preserveDirectives({
71+
include: 'src/DynamicIcon.ts',
72+
suppressPreserveModulesWarning: true,
73+
}),
74+
],
6675
external: ['react', 'prop-types', ...external],
6776
output: {
6877
name: packageName,
@@ -95,7 +104,31 @@ export default [
95104
input: 'src/dynamicIconImports.ts',
96105
output: [
97106
{
98-
file: `dynamicIconImports.d.ts`,
107+
file: `dist/dynamicIconImports.d.ts`,
108+
format: 'es',
109+
},
110+
],
111+
plugins: [
112+
dts({
113+
exclude: ['./src/icons'],
114+
}),
115+
],
116+
},
117+
{
118+
input: 'src/dynamic.ts',
119+
output: [
120+
{
121+
file: `dist/dynamic.d.ts`,
122+
format: 'es',
123+
},
124+
],
125+
plugins: [dts()],
126+
},
127+
{
128+
input: 'src/DynamicIcon.ts',
129+
output: [
130+
{
131+
file: `dist/DynamicIcon.d.ts`,
99132
format: 'es',
100133
},
101134
],

packages/lucide-react/scripts/exportTemplate.mjs

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,9 @@ export default ({ componentName, iconName, children, getSvg, deprecated, depreca
77

88
return `
99
import createLucideIcon from '../createLucideIcon';
10+
import { IconNode } from '../types';
11+
12+
export const __iconNode: IconNode = ${JSON.stringify(children)}
1013
1114
/**
1215
* @component @name ${componentName}
@@ -19,7 +22,7 @@ import createLucideIcon from '../createLucideIcon';
1922
* @returns {JSX.Element} JSX Element
2023
* ${deprecated ? `@deprecated ${deprecationReason}` : ''}
2124
*/
22-
const ${componentName} = createLucideIcon('${componentName}', ${JSON.stringify(children)});
25+
const ${componentName} = createLucideIcon('${componentName}', __iconNode);
2326
2427
export default ${componentName};
2528
`;
Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
'use client';
2+
3+
import { createElement, forwardRef, useEffect, useState } from 'react';
4+
import { IconNode, LucideIcon, LucideProps } from './types';
5+
import dynamicIconImports from './dynamicIconImports';
6+
import Icon from './Icon';
7+
8+
export type DynamicIconModule = { default: LucideIcon; __iconNode: IconNode };
9+
10+
export type IconName = keyof typeof dynamicIconImports;
11+
12+
export const iconNames = Object.keys(dynamicIconImports) as Array<IconName>;
13+
14+
interface DynamicIconComponentProps extends LucideProps {
15+
name: IconName;
16+
fallback?: () => JSX.Element | null;
17+
}
18+
19+
async function getIconNode(name: IconName) {
20+
if (!(name in dynamicIconImports)) {
21+
throw new Error('[lucide-react]: Name in Lucide DynamicIcon not found');
22+
}
23+
24+
// TODO: Replace this with a generic iconNode package.
25+
const icon = (await dynamicIconImports[name]()) as DynamicIconModule;
26+
27+
return icon.__iconNode;
28+
}
29+
30+
/**
31+
* Dynamic Lucide icon component
32+
*
33+
* @component Icon
34+
* @param {object} props
35+
* @param {string} props.color - The color of the icon
36+
* @param {number} props.size - The size of the icon
37+
* @param {number} props.strokeWidth - The stroke width of the icon
38+
* @param {boolean} props.absoluteStrokeWidth - Whether to use absolute stroke width
39+
* @param {string} props.className - The class name of the icon
40+
* @param {IconNode} props.children - The children of the icon
41+
* @param {IconNode} props.iconNode - The icon node of the icon
42+
*
43+
* @returns {ForwardRefExoticComponent} LucideIcon
44+
*/
45+
const DynamicIcon = forwardRef<SVGSVGElement, DynamicIconComponentProps>(
46+
({ name, fallback: Fallback, ...props }, ref) => {
47+
const [iconNode, setIconNode] = useState<IconNode>();
48+
49+
useEffect(() => {
50+
getIconNode(name)
51+
.then(setIconNode)
52+
.catch((error) => {
53+
console.error(error);
54+
});
55+
}, [name]);
56+
57+
if (iconNode == null) {
58+
if (Fallback == null) {
59+
return null;
60+
}
61+
62+
return createElement(Fallback);
63+
}
64+
65+
return createElement(Icon, {
66+
ref,
67+
...props,
68+
iconNode,
69+
});
70+
},
71+
);
72+
73+
export default DynamicIcon;
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
export {
2+
default as DynamicIcon,
3+
iconNames,
4+
type DynamicIconModule,
5+
type IconName,
6+
} from './DynamicIcon';
7+
export { default as dynamicIconImports } from './dynamicIconImports';

0 commit comments

Comments
 (0)