安装
本页面由 PageTurner AI 翻译(测试版)。未经项目官方认可。 发现错误? 报告问题 →
Immer 可作为直接依赖项安装,支持任何 ES5 环境:
Yarn:
yarn add immerNPM:
npm install immerCDN:暴露的全局变量为
immer- Unpkg:
<script src="https://unpkg.com/immer"></script> - JSDelivr:
<script src="https://cdn.jsdelivr.net/npm/immer"></script> - ⚠️ 使用 CDN 时,建议在浏览器中检查 URL 解析的版本号,避免用户未来意外加载新版。请使用类似格式的 URL:https://unpkg.com/immer@6.0.3/dist/immer.umd.production.min.js 来代替。开发环境请将 URL 中的
production.min替换为development。
- Unpkg:
选择 Immer 版本
本节仅适用于版本 6 及以上
为确保 Immer 保持最小体积,非必需功能均设为可选项,需要显式启用。这样在生产环境打包应用时,未使用的功能不会占用空间。
以下功能支持按需启用:
| Feature | Description | Method to call |
|---|---|---|
| Array Methods optimization | Optimizes array method handling for improved performance with array-heavy operations | enableArrayMethods() |
| ES2015 Map and Set support | To enable Immer to operate on the native Map and Set collections, enable this feature | enableMapSet() |
| JSON Patch support | Immer can keep track of all the changes you make to draft objects. This can be useful for communicating changes using JSON patches | enablePatches() |
例如,要在 Map 上使用 produce,需在应用启动时启用此功能:
// In your application's entrypoint
import {enableMapSet} from "immer"
enableMapSet()
// ...later
import {produce} from "immer"
const usersById_v1 = new Map([
["michel", {name: "Michel Weststrate", country: "NL"}]
])
const usersById_v2 = produce(usersById_v1, draft => {
draft.get("michel").country = "UK"
})
expect(usersById_v1.get("michel").country).toBe("NL")
expect(usersById_v2.get("michel").country).toBe("UK")
Immer 基础版 gzip 压缩后约为 3KB。每个启用的插件会增加约 1-2 KB。具体分解如下:
Import size report for immer:
┌───────────────────────┬───────────┬────────────┬───────────┐
│ (index) │ just this │ cumulative │ increment │
├───────────────────────┼───────────┼────────────┼───────────┤
│ import * from 'immer' │ 6908 │ 0 │ 0 │
│ produce │ 4183 │ 4183 │ 0 │
│ enableMapSet │ 4971 │ 4980 │ 797 │
│ enablePatches │ 5335 │ 6097 │ 1117 │
│ enableArrayMethods │ 4768 │ 6659 │ 562 │
└───────────────────────┴───────────┴────────────┴───────────┘
(this report was generated by npmjs.com/package/import-size)
在旧版 JavaScript 环境中使用?
默认情况下 produce 会尝试使用 Proxy 以获得最佳性能。但在老旧 JavaScript 引擎(如 Microsoft Internet Explorer 或 React Native < v0.59/Android 上使用 Hermes 引擎且 RN < 0.64)中,Proxy 不可用。此时 Immer 会回退到 ES5 兼容实现,功能相同但速度稍慢。
自版本 6 起,必须显式调用
enableES5()来启用回退实现版本 10 彻底移除了回退实现,无法在不支持 Proxy 的浏览器/引擎中使用