Appearance
升级到 v9
¥Upgrading to v9
这是从 v8 升级到 v9 的迁移指南。
¥This is the migration guide for upgrading from v8 to v9.
一般重大变化
¥General Breaking Changes
需要 Node v18+
¥Requires Node v18+
由于这些版本已达到其 end-of-life,因此对 Node.js v14 和 v16 的支持已停止。Faker.js v9 至少需要 Node.js v18。
¥Support for Node.js v14 and v16 has been discontinued as these versions have reached their end-of-life. Faker.js v9 requires a minimum of Node.js v18.
升级到 TypeScript v5
¥Upgrade to TypeScript v5
对 TypeScript v4 的支持已停止。Faker v9 至少需要 TypeScript v5。你可以在现在使用 const 泛型类型参数 功能的 helpers 模块中看到这一点。
¥Support for TypeScript v4 has been discontinued. Faker v9 requires a minimum of TypeScript v5. You can see this in action in the helpers module which now uses the const generic type parameters feature.
ts
// v8
faker.helpers.arrayElement([1, 2, 3]); // number
faker.helpers.arrayElement([1, 2, 3] as const); // 1 | 2 | 3
// v9
faker.helpers.arrayElement([1, 2, 3]); // 1 | 2 | 3
修复 Tree Shaking
¥Fix Tree Shaking
在此版本之前,存在一个问题,即使只使用一个语言环境,也会打包所有语言环境。用户不得不采取一种解决方法,从专用路径导入特定的 faker 实例。
¥Prior to this version, there was an issue where all locales would be bundled even if only one was used. Users had to resort to a workaround by importing specific faker instances from dedicated paths.
ts
import { faker } from '@faker-js/faker/locale/de';
通过此修复,解决方法不再是必要的。你将能够从包的根目录中导入不同的本地化 faker 实例,而包仅包含那些特定的语言环境。
¥With this fix, the workaround should no longer be necessary. You will be able to import different localized faker instances from the root of your package with the bundle only including those specific locales.
ts
import { fakerDE, fakerES, fakerFR } from '@faker-js/faker';
专用导入路径保留在 v9 中,以便我们的用户逐步迁移。
¥The dedicated import paths are kept in v9, to allow a gradual migration for our users.
虽然根据语义版本控制指南,这不是重大更改,但它确实会影响用户打包器的行为。
¥While this is not a breaking change according to semantic versioning guidelines, it does impact the behavior of users' bundlers.
默认使用高精度 RNG
¥Use High Precision RNG by Default
在 v9 中,我们从 32 位随机值切换到 53 位随机值。我们不会对底层算法进行太多更改,但现在我们每一步使用两个种子值而不是一个。
¥In v9 we switch from a 32 bit random value to a 53 bit random value. We don't change the underlying algorithm much, but we now consume two seed values each step instead of one.
你可以在我们的博客文章中阅读更多内容:v9.0 中的新功能
¥You can read more in out Blog Post: What's New In v9.0
采用
¥Adoption
如果你没有任何种子测试,而只是想要一些随机值,那么你不必进行任何更改。
¥If you don't have any seeded tests and just want some random values, then you don't have to change anything.
如果你有种子测试,则必须将大多数测试快照或类似的比较更新为新值。
¥If you have seeded tests, you have to update most test snapshots or similar comparisons to new values.
要更新快照或不同测试框架中的类似比较,你可以使用以下命令:
¥For updating snapshots or similar comparisons in different testing frameworks, you can use the following commands:
Vitest:
vitest run --update
Jest:
jest --updateSnapshot
保持旧行为
¥Keeping the Old Behavior
如果你创建自己的 Faker
实例并将 Randomizer
实例从 generateMersenne32Randomizer()
函数传递给它,则可以保留旧行为。
¥You can keep the old behavior, if you create your own Faker
instance and pass a Randomizer
instance from the generateMersenne32Randomizer()
function to it.
ts
import {
Faker,
generateMersenne32Randomizer, // < v9 default
generateMersenne53Randomizer, // > v9 default
} from '@faker-js/faker';
const faker = new Faker({
randomizer: generateMersenne32Randomizer(),
...
});
重组 dist 文件夹
¥Restructured dist folder
dist
文件夹现在包含 CJS 的最小化和分块文件,因为我们在打包过程中切换到 tsup。因此不再可能使用 @faker-js/faker/dist/cjs/...
。但是,由于我们正式支持仅通过 package.json
定义的 exports
,因此这不会影响你的代码。
¥The dist
folder now contains minified and chunked files for CJS, because we switched to tsup for the bundling process. So it is no longer possible to use @faker-js/faker/dist/cjs/...
. However, as we officially support only exports
defined via package.json
, this should not affect your code.
删除弃用的代码
¥Removals of Deprecated Code
v8 中弃用的大量方法在 v9 中被完全删除。为了准备升级,建议首先升级到最新版本的 v8(例如 npm install --save-dev faker@8
)并修复代码触发的任何弃用警告。
¥A large number of methods which were deprecated in v8 are completely removed in v9. To prepare for the upgrade, it is recommended to first upgrade to the latest version of v8 (e.g. npm install --save-dev faker@8
) and fix any deprecation warnings issued by your code.
以下部分包含有关这些更改的更多信息。
¥The following sections contain more information about these changes.
构造函数和 JS 向后兼容方法
¥Constructor and JS Backwards-Compatibility Methods
删除了已弃用的 faker 构造函数,因此你不能再只传递语言环境字符串标识符。
¥Removed deprecated faker constructor, so you can no longer just pass a locale string identifier.
还删除了仅用于 JS 向后兼容的访问器和方法。
¥Also removed the accessors and method that were only for JS backwards compatibility.
get/set locales
get/set locale
get/set localeFallback
setLocale
要使用新的构造函数,你需要传递一个语言环境对象,例如:
¥To use the new constructor, you need to pass a locale object like:
ts
import { Faker, es, base } from '@faker-js/faker';
// A custom faker instance that does not have any fallbacks
const customEsFakerWithoutFallback = new Faker({ locale: es });
// A custom faker instance that has only base-data as fallback, but not english data
const customEsFakerWithFallback = new Faker({ locale: [es, base] });
商务模块
¥Commerce Module
删除了弃用的商业方法
¥Removed deprecated commerce methods
removed | replacement |
---|---|
faker.commerce.price(min, max, dec, symbol) | faker.commerce.price({ min, max, dec, symbol }) |
公司模块
¥Company Module
删除了弃用的公司方法
¥Removed deprecated company methods
removed | replacement |
---|---|
faker.company.suffixes | faker.company.name 的一部分 |
faker.company.companySuffix | faker.company.name 的一部分 |
faker.company.bs | faker.company.buzzPhrase |
faker.company.bsAdjective | faker.company.buzzAdjective |
faker.company.bsBuzz | faker.company.buzzVerb |
faker.company.bsNoun | faker.company.buzzNoun |
公司名称前缀文件重新组织
¥Company Name Affix files reorganized
公司名称后缀文件的使用不一致。有时 suffix
es 被用作模式中的前缀,因为它们包含法人实体类型(在英语中,这些被定义为 suffix
es)。我们重命名了文件以匹配其实际内容而不是假设位置。如果你使用的是公共方法,则无需进行任何更改。如果你正在访问原始定义(例如在 faker.helpers.fake()
中),则只需更改代码。
¥The company name affix files have been used inconsistently. Sometimes suffix
es were used as prefixes in the patterns, because they contained legal entity types (and in English these were defined as suffix
es). We renamed the files to match their actual content instead of their hypothetical position. If you are using the public methods, no changes are required. You only need to change your code if you are accessing the raw definitions e.g. in faker.helpers.fake()
.
之前 | 之后 |
---|---|
company.prefix | company.category |
company.suffix | company.legal_entity_type |
注释
在某些语言环境中,prefix
和 suffix
可能已交换,因此这些语言环境的映射可能不正确。
¥In some locales prefix
es and suffix
es might have been swapped, so the mapping might be wrong for those.
数据类型模块
¥Datatype Module
删除了弃用的数据类型方法
¥Removed deprecated datatype methods
removed | replacement |
---|---|
faker.datatype.number() | faker.number.int() 或 faker.number.float() |
faker.datatype.float() | faker.number.float() |
faker.datatype.datetime({ min, max }) | faker.date.between({ from, to }) 或 faker.date.anytime() |
faker.datatype.string() | faker.string.sample() |
faker.datatype.uuid() | faker.string.uuid() |
faker.datatype.hexadecimal() | faker.string.hexadecimal() 或 faker.number.hex() |
faker.datatype.json() | 你自己的函数来生成复杂对象 |
faker.datatype.array() | 你自己的函数来构建复杂数组 |
faker.datatype.bigInt() | faker.number.bigInt() |
日期模块
¥Date Module
删除了已弃用的日期方法
¥Removed deprecated date methods
removed | replacement |
---|---|
faker.date.past(years, refDate) | faker.date.past({ years, refDate }) |
faker.date.future(years, refDate) | faker.date.future({ years, refDate }) |
faker.date.between(from, to) | faker.date.between({ from, to }) |
faker.date.betweens(from, to, count) | faker.date.betweens({ from, to, count }) |
faker.date.recent(days, refDate) | faker.date.recent({ days, refDate }) |
faker.date.soon(days, refDate) | faker.date.soon({ days, refDate }) |
faker.date.month({ abbr }) | faker.date.month({ abbreviated }) |
faker.date.weekday({ abbr }) | faker.date.weekday({ abbreviated }) |
财务模块
¥Finance Module
删除了已弃用的财务方法
¥Removed deprecated finance methods
removed | replacement |
---|---|
faker.finance.account | faker.finance.accountNumber |
faker.finance.mask | faker.finance.maskedNumber |
faker.finance.amount(min, max, dec, symbol, autoFormat) | faker.finance.amount({ min, max, dec, symbol, autoFormat }) |
faker.finance.iban(formatted, countryCode) | faker.finance.iban({ formatted, countryCode }) |
Git 模块
¥Git Module
删除了已弃用的 git 方法
¥Removed deprecated git methods
removed | replacement |
---|---|
faker.git.shortSha() | faker.git.commitSha({ length: 7 }) |
帮助模块
¥Helpers Module
删除了已弃用的辅助方法
¥Removed deprecated helpers methods
removed | replacement |
---|---|
faker.helpers.replaceSymbolWithNumber | string.replace(/#+/g, (m) => faker.string.numeric(m.length)) |
faker.helpers.regexpStyleStringParse | faker.helpers.fromRegExp |
faker.helpers.unique | import { UniqueEnforcer } from 'enforce-unique'; |
请注意,这些不是完全一样的替换:
¥Note these are not exact replacements:
faker.helpers.replaceSymbolWithNumber
replaceSymbolWithNumber
方法在 Faker v8.4 中已弃用,并在 v9.0 中删除。该方法逐个符号解析给定的字符串,并用数字(0
- 9
)替换 #
符号,用数字 >=2(2
)替换 !
符号 - 9
).这主要由 Faker 在内部用于生成调用号码。如果需要,你可以使用简单的字符串替换结合 faker.string.numeric
来替换它
¥The replaceSymbolWithNumber
method was deprecated in Faker v8.4 and removed in v9.0. The method parsed the given string symbol by symbol and replaces the #
symbol with digits (0
- 9
) and the !
symbol with digits >=2 (2
- 9
). This was primarily used internally by Faker for generating phone numbers. If needed, you can use a simple string replace combined with faker.string.numeric
to replace this
ts
// old
faker.helpers.replaceSymbolWithNumber('#####-##'); // '04812-67'
// new
'#####-##'.replace(/#+/g, (m) => faker.string.numeric(m.length));
// old
faker.helpers.replaceSymbolWithNumber('!#####'); // '123152'
// new
'!#####'
.replace(/#+/g, (m) => faker.string.numeric(m.length))
.replace(/!+/g, (m) =>
faker.string.numeric({ length: m.length, exclude: ['0', '1'] })
);
faker.helpers.regexpStyleStringParse
faker.helpers
中的 regexpStyleStringParse
方法在 Faker v8.1 中已弃用,并在 v9.0 中删除。更强大的 faker.helpers.fromRegExp
可能是可能的替代品。
¥The regexpStyleStringParse
method in faker.helpers
was deprecated in Faker v8.1 and removed in v9.0. A likely replacement is the more powerful faker.helpers.fromRegExp
.
ts
faker.helpers.regexpStyleStringParse('a{3,6}'); // aaaaa
faker.helpers.fromRegExp('a{3,6}'); // aaaaa
但是,请注意,faker.helpers.fromRegExp
并不是 faker.helpers.regexpStyleStringParse
的完全替代品,因为 fromRegExp
无法处理数字范围。现在需要单独处理。
¥However, please note that faker.helpers.fromRegExp
is not an exact replacement for faker.helpers.regexpStyleStringParse
as fromRegExp
cannot handle numeric ranges. This now needs to be handled separately.
ts
faker.helpers.regexpStyleStringParse('a{3,6}[1-100]'); // "aaaa53", etc.
faker.helpers.fromRegExp('a{3,6}') + faker.number.int({ min: 1, max: 100 });
faker.helpers.unique
在 v9 之前,Faker 提供了一种 faker.helpers.unique()
方法,该方法具有全局存储以跟踪重复项。这在 v9 中被删除。
¥Prior to v9, Faker provided a faker.helpers.unique()
method which had a global store to keep track of duplicates. This was removed in v9.
请参阅 唯一值指南 了解替代方案。
¥Please see the unique values guide for alternatives.
例如,许多简单的用例可以使用 faker.helpers.uniqueArray
。或者你可以迁移到推荐的第三方包,例如 enforce-unique
:
¥For example, many simple use cases can use faker.helpers.uniqueArray
. Or you can migrate to a recommended third party package such as enforce-unique
:
基本示例:
¥Basic example:
ts
// OLD
const name = faker.helpers.unique(faker.person.firstName);
// NEW
import { UniqueEnforcer } from 'enforce-unique';
//const { UniqueEnforcer } = require("enforce-unique") // CJS
const enforcerName = new UniqueEnforcer();
const name = enforcerName.enforce(faker.person.firstName);
带有参数:
¥With parameters:
ts
// OLD
const stateCode = faker.helpers.unique(faker.location.state, [
{
abbreviated: true,
},
]);
// NEW
import { UniqueEnforcer } from 'enforce-unique';
const enforcerState = new UniqueEnforcer();
const stateCode = enforcerState.enforce(() =>
faker.location.state({
abbreviated: true,
})
);
带有选项:
¥With options:
ts
// OLD
const city = faker.helpers.unique(faker.location.city, [], {
maxRetries: 100,
maxTime: 1000,
});
// NEW
import { UniqueEnforcer } from 'enforce-unique';
const enforcer = new UniqueEnforcer();
const city = enforcer.enforce(faker.location.city, {
maxRetries: 100,
maxTime: 1000,
});
注释
enforce-unique
不直接支持以前在 faker.helpers.unique
中可用的 store
选项。如果你以前使用过此参数,请检查 documentation。如果你需要重置存储,则可以在 UniqueEnforcer
实例上调用 reset()
方法。
¥enforce-unique
does not directly support the store
option previously available in faker.helpers.unique
. If you were previously using this parameter, check the documentation. If you need to reset the store, you can call the reset()
method on the UniqueEnforcer
instance.
faker.helpers.arrayElement
和 faker.helpers.arrayElements
¥faker.helpers.arrayElement
and faker.helpers.arrayElements
以下内容仅影响 Javascript 中的使用,因为在 Typescript 中,这种使用已经会引发编译时错误。
¥The following only affects usage in Javascript, as in Typescript this usage would already throw a compile-time error.
以前,当不带参数调用 arrayElement
和 arrayElements
方法时,它们会抛出专用错误。
¥Previously, the arrayElement
and arrayElements
methods would throw a dedicated error, when called without arguments.
ts
faker.helpers.arrayElement(undefined); // FakerError: Calling `faker.helpers.arrayElement()` without arguments is no longer supported.
现在,它会抛出一个 JS 原生错误:
¥Now, it throws a JS native error:
ts
faker.helpers.arrayElement(undefined); // TypeError: Cannot read properties of undefined (reading 'length')
使用空数组调用方法仍然像以前一样运行。
¥Calling the methods with an empty array instead still behaves as before.
图片模块
¥Image Module
删除了已弃用的图片方法
¥Removed deprecated image methods
removed | replacement |
---|---|
faker.image.image() | faker.image.url() |
faker.image.imageUrl() | faker.image.url() |
faker.image.abstract() | faker.image.urlLoremFlickr({ category: 'abstract' }) 或 faker.image.url() |
faker.image.animals() | faker.image.urlLoremFlickr({ category: 'animals' }) 或 faker.image.url() |
faker.image.business() | faker.image.urlLoremFlickr({ category: 'business' }) 或 faker.image.url() |
faker.image.cats() | faker.image.urlLoremFlickr({ category: 'cats' }) 或 faker.image.url() |
faker.image.city() | faker.image.urlLoremFlickr({ category: 'city' }) 或 faker.image.url() |
faker.image.food() | faker.image.urlLoremFlickr({ category: 'food' }) 或 faker.image.url() |
faker.image.nightlife() | faker.image.urlLoremFlickr({ category: 'nightlife' }) 或 faker.image.url() |
faker.image.fashion() | faker.image.urlLoremFlickr({ category: 'fashion' }) 或 faker.image.url() |
faker.image.people() | faker.image.urlLoremFlickr({ category: 'people' }) 或 faker.image.url() |
faker.image.nature() | faker.image.urlLoremFlickr({ category: 'nature' }) 或 faker.image.url() |
faker.image.sports() | faker.image.urlLoremFlickr({ category: 'sports' }) 或 faker.image.url() |
faker.image.technics() | faker.image.urlLoremFlickr({ category: 'technics' }) 或 faker.image.url() |
faker.image.transport() | faker.image.urlLoremFlickr({ category: 'transport' }) 或 faker.image.url() |
图片提供者
¥Image Providers
从 faker.image
中删除了已弃用的图片提供程序。无论如何,它们已经返回了损坏的图片 URL。
¥Removed deprecated image providers from faker.image
. They already returned broken image URLs anyway.
removed | replacement |
---|---|
faker.image.lorempicsum.image | faker.image.urlPicsumPhotos |
faker.image.lorempicsum.imageGrayscale | faker.image.urlPicsumPhotos({ grayscale: true }) |
faker.image.lorempicsum.imageBlurred | faker.image.urlPicsumPhotos({ blur: 4 }) |
faker.image.lorempicsum.imageRandomSeeded | faker.image.urlPicsumPhotos |
faker.image.lorempicsum.imageUrl | faker.image.urlPicsumPhotos |
faker.image.placeholder.imageUrl | faker.image.urlPlaceholder |
faker.image.placeholder.randomUrl | faker.image.urlPlaceholder |
faker.image.unsplash.image | faker.image.url |
faker.image.unsplash.imageUrl | faker.image.url |
faker.image.unsplash.food | faker.image.urlLoremFlickr({ category: 'food' }) |
faker.image.unsplash.people | faker.image.urlLoremFlickr({ category: 'people' }) |
faker.image.unsplash.nature | faker.image.urlLoremFlickr({ category: 'nature' }) |
faker.image.unsplash.technology | faker.image.urlLoremFlickr({ category: 'technology' }) |
faker.image.unsplash.objects | faker.image.urlLoremFlickr({ category: 'objects' }) |
faker.image.unsplash.buildings | faker.image.urlLoremFlickr({ category: 'buildings' }) |
互联网模块
¥Internet Module
删除了已弃用的互联网方法
¥Removed deprecated internet methods
removed | replacement |
---|---|
faker.internet.avatar() | faker.image.avatarLegacy() 或 faker.image.avatar() |
faker.internet.email(firstName, lastName, provider, options) | faker.internet.email({ firstName, lastName, provider, ... }) |
faker.internet.exampleEmail(firstName, lastName, options) | faker.internet.exampleEmail({ firstName, lastName, ... }) |
faker.internet.userName(firstName, lastName) | faker.internet.userName({ firstName, lastName }) |
faker.internet.displayName(firstName, lastName) | faker.internet.displayName({ firstName, lastName }) |
faker.internet.color(redBase, greenBase, blueBase) | faker.internet.color({ redBase, greenBase, blueBase }) |
faker.internet.password(length, memorable, pattern, prefix) | faker.internet.password({ length, memorable, pattern, prefix }) |
位置模块
¥Location Module
删除了已弃用的定位方法
¥Removed deprecated location methods
removed | replacement |
---|---|
faker.location.zipCodeByState | faker.location.zipCode({ state }) |
faker.location.cityName | faker.location.city |
faker.location.streetName | faker.location.street |
faker.location.stateAbbr() | faker.location.state({ abbreviated: true }) |
faker.location.latitude(max, min, precision) | faker.location.latitude({ max, min, precision }) |
faker.location.longitude(max, min, precision) | faker.location.longitude({ max, min, precision }) |
faker.location.direction(abbreviated) | faker.location.direction({ abbreviated }) |
faker.location.cardinalDirection(abbreviated) | faker.location.cardinalDirection({ abbreviated }) |
faker.location.ordinalDirection(abbreviated) | faker.location.ordinalDirection({ abbreviated }) |
faker.location.nearbyGPSCoordinate(coordinate, radius, isMetric) | faker.location.nearbyGPSCoordinate({ origin, radius, isMetric }) |
方向定义重新组织
¥Direction definitions reorganized
faker.location.direction()
、faker.location.cardinalDirection()
和 faker.location.ordinalDirection()
使用的语言环境定义已重新组织。以前,它们位于 definitions.location.direction
和 definitions.location.direction_abbr
下,并且它们的值必须按特定顺序排列。现在,所有值都嵌套在 definitions.location.direction
下,并带有描述性属性名称。如果你使用的是公共方法,则无需进行任何更改。如果你正在访问原始定义(例如在 faker.helpers.fake()
中),则只需更改代码。
¥The locale definitions used by faker.location.direction()
, faker.location.cardinalDirection()
and faker.location.ordinalDirection()
have been reorganized. Previously, they were located under definitions.location.direction
and definitions.location.direction_abbr
and their values were required to be in a specific order. Now, all values are nested under definitions.location.direction
with descriptive property names. If you are using the public methods, no changes are required. You only need to change your code if you are accessing the raw definitions e.g. in faker.helpers.fake()
.
之前 | 之后 |
---|---|
location.direction | location.direction.cardinal 或 location.direction.ordinal |
location.direction_abbr | location.direction.cardinal_abbr 或 location.direction.ordinal_abbr |
默认国家/地区定义已删除
¥Default country definitions removed
faker.definitions.location.default_country
定义已被删除,因为它们未被任何公共方法使用,并且对于不直接对应于单个国家/地区的语言环境(如 ar
)没有用。
¥The faker.definitions.location.default_country
definition has been removed, as they were not used by any public method, and were not useful for locales which don't correspond directly to a single country, like ar
.
数字模块
¥Number Module
删除了已弃用的数字参数
¥Removed deprecated number parameter
removed | replacement |
---|---|
faker.number.float({ precision }) | faker.number.float({ multipleOf }) |
人员模块
¥Person Module
更改的定义
¥Changed Definitions
faker.person.jobTitle()
、faker.person.jobDescriptor()
、faker.person.jobArea()
和 faker.person.jobType()
使用的语言环境定义已重新组织,不再嵌套在 definitions.person.title
下。相反,faker.person.firstName()
、faker.person.lastName()
、faker.person.middleName()
和 faker.person.prefix()
使用的性别语言环境定义现在合并在单个定义属性下。如果你使用的是公共方法,则无需进行任何更改。如果你正在访问原始定义(例如在 faker.helpers.fake()
中),则只需更改代码。
¥The locale definitions used by faker.person.jobTitle()
, faker.person.jobDescriptor()
, faker.person.jobArea()
and faker.person.jobType()
have been reorganized and are no longer nested under definitions.person.title
. Conversely, the gendered locale definitions used by faker.person.firstName()
, faker.person.lastName()
, faker.person.middleName()
and faker.person.prefix()
are now consolidated under a single definition property. If you are using the public methods, no changes are required. You only need to change your code if you are accessing the raw definitions e.g. in faker.helpers.fake()
.
之前 | 之后 |
---|---|
person.female_first_name | person.first_name.female |
person.female_last_name_pattern | person.last_name_pattern.female |
person.female_last_name | person.last_name.female |
person.female_middle_name | person.middle_name.female |
person.female_prefix | person.prefix.female |
person.first_name | person.first_name.generic |
person.last_name_pattern | person.last_name_pattern.generic |
person.last_name | person.last_name.generic |
person.male_first_name | person.first_name.male |
person.male_last_name_pattern | person.last_name_pattern.male |
person.male_last_name | person.last_name.male |
person.male_middle_name | person.middle_name.male |
person.male_prefix | person.prefix.male |
person.middle_name | person.middle_name.generic |
person.prefix | person.prefix.generic |
person.title.descriptor | person.job_descriptor |
person.title.job | person.job_type |
person.title.level | person.job_area |
调用模块
¥Phone Module
删除了已弃用的调用方法
¥Removed deprecated phone methods
removed | replacement |
---|---|
faker.phone.number(format) | faker.phone.number(style) 、faker.string.numeric() 或 faker.helpers.fromRegExp() |
随机模块
¥Random Module
删除了已弃用的随机模块
¥Removed deprecated random module
removed | replacement |
---|---|
faker.random.alpha() | faker.string.alpha() |
faker.random.alphaNumeric() | faker.string.alphanumeric() |
faker.random.locale() | faker.helpers.objectKey(allLocales/allFakers) |
faker.random.numeric() | faker.string.numeric() |
faker.random.word() | faker.lorem.word() 或 faker.word.sample() |
faker.random.words() | faker.lorem.words() 或 faker.word.words() |
区域设置别名
¥Locale Aliases
重命名已弃用的语言环境别名 cz
、en_IND
、ge
并删除了 global
。
¥Renamed deprecated locale aliases cz
, en_IND
, ge
and removed global
.
removed | replacement |
---|---|
import { faker } from '@faker-js/faker/locale/cz' | import { faker } from '@faker-js/faker/locale/cs_CZ' |
import { faker } from '@faker-js/faker/locale/en_IND' | import { faker } from '@faker-js/faker/locale/en_IN' |
import { faker } from '@faker-js/faker/locale/ge' | import { faker } from '@faker-js/faker/locale/ka_GE' |
import { faker } from '@faker-js/faker/locale/global' | import { faker } from '@faker-js/faker/locale/base' |
重命名语言环境定义
¥Renamed Locale Definitions
以下语言环境定义已调整为与 Faker 的语言环境定义命名标准一致:
¥The following locale definitions have been adjusted to align with Faker's locale definition naming standard:
removed | replacement |
---|---|
faker.definitions.science.chemicalElement | faker.definitions.science.chemical_element |
faker.definitions.system.directoryPaths | faker.definitions.system.directory_path |
faker.definitions.system.mimeTypes | faker.definitions.system.mime_type |
faker.definitions.lorem.words | faker.definitions.lorem.word |
现在,我们所有的语言环境数据都使用以下命名方案:
¥With that now all our locale data use the following naming scheme:
txt
faker.definitions.category_name.entry_name
请记住,复杂对象的属性键仍采用驼峰式命名。
¥Please keep in mind that property keys of complex objects remain in camel-case.
txt
faker.definitions.science.chemical_element.atomicNumber
类型别名
¥Type Aliases
删除了已弃用的类型别名
¥Removed deprecated type aliases
removed | replacement |
---|---|
AddressDefinitions | LocationDefinition |
AirlineDefinitions | AirlineDefinition |
AnimalDefinitions | AnimalDefinition |
ColorDefinitions | ColorDefinition |
CommerceDefinitions | CommerceDefinition |
CommerceProductNameDefinitions | CommerceProductNameDefinition |
CompanyDefinitions | CompanyDefinition |
DatabaseDefinitions | DatabaseDefinition |
DateDefinitions | DateDefinition |
FinanceDefinitions | FinanceDefinition |
HackerDefinitions | HackerDefinition |
InternetDefinitions | InternetDefinition |
LoremDefinitions | LoremDefinition |
MusicDefinitions | MusicDefinition |
NameDefinitions | PersonDefinition |
PhoneNumberDefinitions | PhoneNumberDefinition |
ScienceDefinitions | ScienceDefinition |
SystemDefinitions | SystemDefinition |
SystemMimeTypeEntryDefinitions | SystemMimeTypeEntryDefinition |
VehicleDefinitions | VehicleDefinition |
WordDefinitions | WordDefinition |
CSSFunction | CssFunctionType |
CSSSpace | CssSpaceType |
AddressModule | LocationModule |
NameModule | PersonModule |
特定方法的重大更改
¥Breaking Changes to Specific Methods
生日新默认模式
¥Birthdate New Default Mode
以前,faker.date.birthdate()
方法的默认值在其具体影响上不明确。现在,该方法不需要 min
、max
和 mode
选项中的任何一个或全部。
¥Previously, the faker.date.birthdate()
method had defaults that were unclear in their specific impact. Now, the method requires either none or all of the min
, max
and mode
options.
我们还改进了错误消息,以清楚地指示何时必须同时设置 min
、max
和 mode
选项。
¥We also improved the error messages to clearly indicate when the min
, max
, and mode
options must be set together.
无效日期失败
¥Fail on Invalid Dates
faker.date
模块中的各种方法允许你传递 Date
值:也就是说,无论是 Javascript 日期,还是可以通过 new Date()
构造函数转换为 Date
的时间戳数字或字符串。
¥Various methods in the faker.date
module allow you to pass a Date
-ish value: that is, either a Javascript Date, or a timestamp number or string that can be converted to a Date
via the new Date()
constructor.
以前,如果你将无法解析的内容传递给 Date
,它将回退到当前参考日期。现在,这会抛出一个错误,提高人们对该错误值的认识。
¥Previously, if you passed something which could not be parsed to a Date
, it would fall back to the current reference date. Now, this throws an error raising awareness of that bad value.
这会影响 anytime()
、birthdate()
、past()
、future()
、recent()
和 soon()
方法的 refDate
参数以及 between()
和 betweens()
的 from
和 to
参数。
¥This affects the refDate
parameter of the anytime()
, birthdate()
, past()
, future()
, recent()
and soon()
, methods as well as the from
and to
parameters of between()
and betweens()
.
单独的时区方法
¥Separate Timezone Methods
timeZone
功能已被划分以增强特异性:
¥The timeZone
functionality has been divided to enhance specificity:
使用
faker.date.timeZone()
生成随机的全局时区。¥Use
faker.date.timeZone()
to generate a random global time zone.使用
faker.location.timeZone()
获取特定于当前语言环境的时区。¥Use
faker.location.timeZone()
to obtain time zone specific to the current locale.
我们尚未更新所有与地区相关的时区数据,因此如果你遇到意外值,请使用 创建新问题。
¥We haven't updated all locale dependent time zone data yet, so if you encounter unexpected values, please create a new issue.
价格现在返回更多类似价格的值
¥Prices Now Return More Price-Like Values
faker.commerce.price()
方法现在生成的值也返回小数值。
¥The faker.commerce.price()
method now produces values that also return fractional values.
旧价格:828.00 新价格:828.59
¥Old price: 828.00 New price: 828.59
价格的最后一位数字已调整为更像价格:
¥The last digit of the price is adjusted to be more price-like:
50%时间:
9
¥50% of the time:
9
30% 的时间:
5
¥30% of the time:
5
10% 的时间:
0
¥10% of the time:
0
10% 的时间:从
0
到9
的随机数字¥10% of the time: a random digit from
0
to9
我们计划在未来重新考虑这种方法:#2579
¥We plan to rethink this method some more in the future: #2579
图片默认有随机选项
¥Images Have Random Options by Default
以前,某些图片方法具有静态默认参数。这些已被更改为返回更多不同的 URL。下面你可以找到一个带有片段的表格,以获取以前的行为:
¥Some of image methods had static default parameters, previously. These have been changed to return more divers urls. Following you can find a table with snippets to obtain the previous behavior:
方法 | 旧默认值 |
---|---|
faker.image.url() | {width: 640, height: 480} |
faker.image.urlLoremFlickr() | {width: 640, height: 480} |
faker.image.urlPicsumPhotos() | {width: 640,height: 480, blur: 0, grayscale: false} |
faker.image.dataUri() | {width: 640, height: 480, type: 'svg-uri'} |
在 faker.date.between
和 betweens
中需要 from
和 to
¥Require from
and to
in faker.date.between
and betweens
以前,在 faker.date.between()
和 faker.date.betweens()
中,如果省略了 from
或 to
参数(在 Javascript 中)或无效日期(在 Javascript 或 Typescript 中),它们将默认为当前日期或参考日期。现在,必须明确给出两个边界。如果你仍然需要旧的行为,你可以传递 Date.now()
或 from
或 to
的参考日期。
¥Previously, in faker.date.between()
and faker.date.betweens()
if the from
or to
parameter was omitted (in Javascript) or an invalid date (in Javascript or Typescript), they would default to the current date or reference date. Now, both boundaries must be given explicitly. If you still need the old behavior, you can pass Date.now()
or the reference date for from
or to
.
对传递给 faker.helpers.multiple
方法的函数签名进行更严格的检查
¥Stricter Checking for Function Signature Passed to faker.helpers.multiple
Method
faker.helpers.multiple
方法将函数引用作为其第一个参数。以前你可能编写过这样的代码来生成多个值。 =
¥The faker.helpers.multiple
method takes a function reference as its first parameter. Previously you may have written code like this to generate multiple values.
ts
faker.helpers.multiple(faker.date.past, { count: 2 });
但是这段代码有一个错误 - faker.helpers.multiple
将循环索引作为第二个参数传递给方法,在本例中,该方法将 faker.date.past()
调用的 refDate
设置为 0,使所有日期都早于 1970 年。
¥However this code has a bug - faker.helpers.multiple
passes the loop index as the second parameter to the method, which in this case would set the refDate
of the faker.date.past()
call to 0, making all dates before 1970.
相反,你通常应该使用类似这样的 lambda 函数
¥Instead you should generally use a lambda function like
ts
faker.helpers.multiple(() => faker.date.past(), { count: 2 });
以获得所需的行为。在 v9.0 中,我们在 Typescript 中使用更严格的类型检查来检测何时调用与 (v: unknown, index: number)
不兼容的函数,这可能会在以前可能存在运行时错误的地方导致编译时错误。
¥to get the desired behavior. In v9.0, we use stricter type-checking in Typescript to detect when a function is called which is not compatible with (v: unknown, index: number)
which can cause compile-time errors in places where previously there were potential runtime errors.
糟糕
¥Bad
ts
faker.helpers.multiple(faker.person.firstName, ...); // ❗
// In Typescript, this is now a compile time error
// Argument of type '(sex?: "female" | "male" | undefined) => string'
// is not assignable to parameter of type '(v: unknown, index: number) => unknown'.
很好
¥Good
ts
faker.helpers.multiple(() => faker.person.firstName(), ...); // ✔
新类型还允许更简单的用例,其中索引是生成数据的一部分,例如作为 id。
¥The new types also allow for easier use-cases where the index is part of the generated data e.g. as id.
ts
faker.helpers.multiple((_, index) => ({ id: index, ...}), ...); // [{id: 0, ...}, ...]
更严格的枚举值使用
¥Stricter Enum Value Usage
当为枚举参数传递未知值时,某些方法以前会回退到选项的默认值。现在,这些方法反而返回未定义。这只会影响 Javascript 中的使用,因为在 Typescript 中,这种使用已经会引发编译时错误。
¥Some methods would previously fallback to a default value for an option when an unknown value was passed for a enum parameter. Now, these methods return undefined instead. This only affects usage in Javascript, as in Typescript this usage would already throw a compile-time error.
例如:
¥For example:
ts
faker.color.rgb({ format: 'unexpectedvalue' });
// in Faker v8, is [110, 82, 190] like { format: "decimal" }
// in Faker v9, is undefined
这会影响:
¥This affects:
如果提供,
faker.color.rgb()
的format
属性必须是'binary' | 'css' | 'decimal' | 'hex'
之一¥The
format
property offaker.color.rgb()
must be one of'binary' | 'css' | 'decimal' | 'hex'
if provided如果提供,
faker.color.cmyk()
、faker.color.hsl()
、faker.color.hwb()
、faker.color.lab()
、faker.color.lch()
的format
属性必须是'binary' | 'css' | 'decimal'
之一¥The
format
property offaker.color.cmyk()
,faker.color.hsl()
,faker.color.hwb()
,faker.color.lab()
,faker.color.lch()
must be one of'binary' | 'css' | 'decimal'
if provided如果提供,
faker.location.countryCode()
的variant
属性必须是alpha-2
、alpha-3
、numeric
之一¥The
variant
property offaker.location.countryCode()
must be one ofalpha-2
,alpha-3
,numeric
if provided如果提供,
faker.string.alpha()
和faker.string.alphanumeric()
的casing
属性必须是'upper' | 'lower' | 'mixed'
之一¥The
casing
property offaker.string.alpha()
andfaker.string.alphanumeric()
must be one of'upper' | 'lower' | 'mixed'
if provided