@bem-react/di

中文文档
6.1.1发布于 2026/08/18MPL-2.0TypeScriptESM + CJS零依赖近 30 天下载 2.9万

BEM React Dependency Injection

原始使用文档
文档目录5 节
  1. Install
  2. Quick start
  3. Replacing components
  4. Extending components
  5. Storing other

@bem-react/di · npm (scoped) npm bundle size (minified + gzip)

Dependency Injection (DI) allows you to split React components into separate versions and comfortably switch them in the project whenever needed, e.g., to make a specific bundle.

DI package helps to solve similar tasks with minimum effort:

  • decouple desktop and mobile versions of a component
  • implement an experimental version of a component alongside the common one
  • store components and their auxiliaries (like settings and functions) in a single place

Install

npm i -S @bem-react/di

Quick start

Note! This example uses @bem-react/classname package.

E.g., for a structure like this:

Components/
  Header/
    [email protected]
    [email protected]
  Footer/
    [email protected]
    [email protected]
App.tsx

First, create two files that define two versions of the App and use different sets of components: [email protected] and [email protected]. Put them near App.tsx.

In each App version ([email protected] and [email protected]) we should define which components should be used. Three steps to do this:

  1. Create a registry with a particular id:
const registry = new Registry({ id: cnApp() })
  1. Register all the needed components versions under a descriptive key (keys, describing similar components, should be the same across all the versions):
registry.set('Header', Header)
registry.set('Footer', Footer)

or

registry.fill({
  Header,
  Footer,
})

or

registry.fill({
  'id-1': Header,
  'id-2': Footer,
})
  1. Export the App version with its registry of components:
export const AppNewVersion = withRegistry(registry)(AppCommon)

The files should look like this:

1. In App.tsx

import { cn } from '@bem-react/classname'

export const cnApp = cn('App')
export const registryId = cnApp()

2. In [email protected]

import { Registry, withRegistry } from '@bem-react/di'
import { App as AppCommon, registryId } from './App'

import { Footer } from './Components/Footer/Footer@desktop'
import { Header } from './Components/Header/Header@desktop'

export const registry = new Registry({ id: registryId })

registry.set('Header', Header)
registry.set('Footer', Footer)

export const AppDesktop = withRegistry(registry)(AppCommon)

3. In [email protected]

import { Registry, withRegistry } from '@bem-react/di'
import { App as AppCommon, registryId } from './App'

import { Footer } from './Components/Footer/Footer@mobile'
import { Header } from './Components/Header/Header@mobile'

export const registry = new Registry({ id: registryId })

registry.set('Header', Header)
registry.set('Footer', Footer)

export const AppMobile = withRegistry(registry)(AppCommon)

Time to use these versions in your app dynamically!

If in App.tsx your dependencies were static before

import React from 'react'
import { cn } from '@bem-react/classname'
import { Header } from './Components/Header/Header'
import { Footer } from './Components/Footer/Footer'

export const App = () => (
  <>
    <Header />
    <Footer />
  </>
)

Now the dependencies can be injected based on the currently used registry

with RegistryConsumer

import React from 'react'
import { cn } from '@bem-react/classname'
import { RegistryConsumer } from '@bem-react/di'

// No Header or Footer imports

const cnApp = cn('App')

export const App = () => (
  <RegistryConsumer id={cnApp()}>
    {({ Header, Footer }) => (
      <>
        <Header />
        <Footer />
      </>
    )}
  </RegistryConsumer>
)

with useRegistry (require react version 16.8.0+)

import React from 'react'
import { cn } from '@bem-react/classname'
import { useRegistry } from '@bem-react/di'

// No Header or Footer imports

const cnApp = cn('App')

export const App = () => {
  const { Header, Footer } = useRegistry(cnApp())

  return (
    <>
      <Header />
      <Footer />
    </>
  )
}

So you could use different versions of your app e.g. for conditional rendering on your server side or to create separate bundles

import { AppDesktop } from './path-to/App@desktop'
import { AppMobile } from './path-to/App@mobile'

Replacing components

Components inside registry can be replaced (e.g. for experiments) by wrapping withRegistry(...)(App) with another registry.

import { Registry, withRegistry } from '@bem-react/di'

import { AppDesktop, registryId } from './App@desktop'
import { HeaderExperimental } from './experiments/Components/Header/Header'

const expRegistry = new Registry({ id: registryId })

// replacing original Header with HeaderExperimental
expRegistry.set('Header', HeaderExperimental)

// AppDesktopExperimental will call App with HeaderExperimental as 'Header'
export const AppDesktopExperimental = withRegistry(expRegistry)(AppDesktop)

When App extracts components from registry DI actually takes all registries defined above and merges. By default higher defined registry overrides lower defined one.

If at some point you want to create registry that wan't be overrided just call the constructor with overridable: false.

const boldRegistry = new Registry({ id: cnApp(), overridable: false })

Extending components

You can extend (e.g. for experiments) a component using method extends(...) in overridden registry.

import { Registry, withRegistry, withBase } from '@bem-react/di'
import { AppDesktop, registryId } from './App@desktop'

const expRegistry = new Registry({ id: registryId })

// extends original Header
expRegistry.extends('Header', (BaseHeader) => (props) => (
  <div>
    <BaseHeader height={200} color={red} />
  </div>
))

// AppDesktopExperimental will call App with extended 'Header'
export const AppDesktopExperimental = withRegistry(expRegistry)(AppDesktop)

DI merges nested registries composing and ordinary components for you. So you always can get a reference to previous component's implementation.

Storing other

DI registry may keep not only components but also their settings and any other auxiliaries (like functions).

import { useRegistry } from '@bem-react/di'

const cnHeader = cn('Header')

export const Header = (props) => {
  const { theme, showNotification, prepareProps } = useRegistry(cnApp())

  // one function is used to fulfill props
  const { title, username } = prepareProps(props)

  useEffect(() => {
    // another function is used inside hook
    showNotification()
  })

  return (
    <header className={cnHeader({ theme })}>
      <h1>{title}</h1>
      <h2>Greetings ${username}</h2>
    </header>
  )
}

版本与发布记录

@bem-react/di 共发布 51 个版本,首次发布于 2018/08/29;过去 12 个月发布了 4 个版本。

版本发布日期距今
6.1.1latest2026/08/182 个月前
6.1.02026/02/278 个月前
6.0.1-dev.1next2026/02/258 个月前
6.0.02026/02/069 个月前
5.1.02025/06/151.4 年前
5.0.1-dev.62025/06/111.4 年前

关于 @bem-react/di 的常见问题

@bem-react/di 是什么?

BEM React Dependency Injection

如何安装 @bem-react/di?

在项目目录运行 npm install @bem-react/di,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:react(^19.0.0)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@bem-react/di 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@bem-react/di 支持 ESM 还是 CommonJS?

同时提供 ES Module 与 CommonJS 入口,import 和 require() 都可以使用,打包工具会自动选择合适的版本。

@bem-react/di 可以商用吗?

@bem-react/di 使用 MPL-2.0 许可。弱 Copyleft:可以商用,也可以和闭源代码一起使用;但如果分发时修改了 MPL 授权的文件,这些文件的修改需以 MPL 开源。以上为概括,不构成法律意见,请以许可原文为准。

@bem-react/di 的下载量有多少?

根据 npm 官方下载统计,@bem-react/di 在 2026/10/08 – 2026/11/06 这 30 天内被下载 28,642 次,日均约 955 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@bem-react/di 还在维护吗?

最新版本 6.1.1 发布于 2026/08/18(2 个月前);至今共发布 51 个版本,其中过去 12 个月发布了 4 个;首次发布于 2018/08/29。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。