Skip to content

优化 ​

🌐 Optimizations

默认情况下,你是从 lucide-react-native 入口点导入图标的:

🌐 By default you import icons from the lucide-react-native entry point:

jsx
import { Camera } from 'lucide-react-native';

这很方便,但它依赖打包工具对入口点(一个重新导出每个图标的“桶”文件)进行_摇树优化_,这样你实际使用的图标才会出现在你的包里。

🌐 This is convenient, but it relies on the bundler to tree-shake the entry point (a "barrel" file that re-exports every icon) so that only the icons you actually use end up in your bundle.

在原生平台上,这通常没问题。但在 网页导出 时可能会有问题,因为 Metro 打包器目前在对桶式导入做 tree-shaking 时表现不佳,可能会把 所有 图标都包含在最终的包里。

🌐 On native platforms this is usually fine. On web exports it can be a problem, because the Metro bundler is currently not very good at tree-shaking barrel imports and may include all icons in your final bundle.

Metro 的摇树限制 ​

🌐 The Metro tree-shaking limitation

当你使用 Expo (expo export --platform web) 为网页构建时,Metro 会被用来打包你的 JavaScript。Metro 会按需打包模块,而且默认情况下不会从一个桶文件中移除未使用的导出。

🌐 When you build for web with Expo (expo export --platform web), Metro is used to bundle your JavaScript. Metro bundles modules on-demand and, by default, does not remove unused exports from a barrel file.

这意味着像下面这样的导入可以引入整个图标集,尽管实际上只渲染了一个图标:

🌐 This means an import like the one below can pull in the entire icon set, even though only a single icon is rendered:

jsx
// May bundle every Lucide icon on web exports
import { Camera } from 'lucide-react-native';

Expo 记录了一种针对 React Native web 导入 和 移除未使用的导入和导出 的实验性优化。实际上,这种 tree-shaking 目前对 lucide-react-native 桶式导入并不能可靠工作,所以 web 导出中的未使用图标不会被移除。

🌐 Expo documents an experimental optimization for React Native web imports and for removing unused imports and exports. In practice this tree-shaking does not currently work reliably for lucide-react-native barrel imports, so the unused icons are not removed from web exports.

🌐 Recommended: import icons individually

为了保证只有你使用的图标被打包——不管打包工具的 tree-shaking 功能如何——直接从各自的模块中导入每个图标:

🌐 To guarantee that only the icons you use are bundled — regardless of the bundler's tree-shaking capabilities — import each icon directly from its own module:

jsx
import Camera from 'lucide-react-native/icons/camera';

// Usage
const App = () => {
  return <Camera />;
};

export default App;

因为每个图标都存在自己的文件里,打包工具只会包含你明确导入的图标。这样可以在不依赖Metro实验性树摇的情况下,让你的网页导出文件保持小巧。

🌐 Because each icon lives in its own file, the bundler only ever includes the icons you explicitly import. This keeps your web export small without depending on Metro's experimental tree-shaking.

图标模块名称是图标名称的kebab-case版本。例如,ArrowRight 图标是从 lucide-react-native/icons/arrow-right 导入的:

🌐 The icon module name is the kebab-case version of the icon name. For example, the ArrowRight icon is imported from lucide-react-native/icons/arrow-right:

jsx
import ArrowRight from 'lucide-react-native/icons/arrow-right';

TIP

单个图标导入在原生和网页上表现完全一样,所以你可以在整个项目中放心使用这种方式,让每个平台的打包尽可能小。