@faker-js/faker vs faker
Generating Realistic Mock Data in JavaScript Applications
@faker-js/fakerfaker类似的npm包:

Generating Realistic Mock Data in JavaScript Applications

@faker-js/faker and faker are both libraries designed to generate realistic fake data for testing, prototyping, and development workflows. They provide utilities for creating mock names, addresses, phone numbers, dates, internet identifiers (like emails and URLs), and more. While they share a common origin, their current implementations, maintenance status, and API design have diverged significantly. Understanding these differences is critical when selecting a library for long-term project stability and developer experience.

npm下载趋势

3 年

统计详情

npm包名称
下载量
Stars
大小
Issues
发布时间
License
@faker-js/faker11,219,10014,9764.72 MB1241 个月前MIT
faker1,979,083-10.1 MB--MIT

@faker-js/faker vs faker: A Practical Guide for Modern Frontend Teams

Both @faker-js/faker and faker help developers generate realistic-looking dummy data — useful for populating UI prototypes, writing integration tests, or seeding local databases during development. But despite similar names and overlapping functionality, they represent very different engineering choices today. Let’s cut through the confusion.

⚠️ Maintenance Status: Active vs Deprecated

The most critical difference isn’t technical — it’s about project health.

faker (the original package) is officially deprecated. Its npm page clearly states: "This package is no longer maintained. Please use @faker-js/faker instead." The GitHub repo archive notice confirms this. No security patches, bug fixes, or feature updates are planned.

@faker-js/faker is the community-driven fork that took over active development. It’s under regular maintenance, accepts contributions, and publishes frequent releases with improvements and new locales.

🛑 Bottom line: Never start a new project with faker. You’re signing up for technical debt from day one.

🧱 Architecture: Modular vs Global Singleton

How each library is structured affects bundle size, test isolation, and flexibility.

faker uses a global singleton. Once imported, it modifies a shared instance. This causes problems in tests where you can’t easily reset or isolate faker behavior between test cases.

// faker: global state (problematic in tests)
import faker from 'faker';

faker.seed(123);
console.log(faker.name.firstName()); // Always the same if seeded

// But another test file might change the seed unintentionally!

@faker-js/faker exports a factory function (faker) that creates isolated instances. You can have multiple fakers with different seeds or locales in the same app — perfect for parallelized test suites.

// @faker-js/faker: explicit instance control
import { faker } from '@faker-js/faker';

const testFaker = faker({ locale: 'en' });
testFaker.seed(123);
console.log(testFaker.person.firstName()); // Predictable and isolated

This shift eliminates hidden global state, making your mocks more predictable and your tests less flaky.

🔤 API Design: Consistent Namespacing vs Legacy Structure

Over time, the original faker API became inconsistent — some methods lived under name, others under internet, with unclear grouping.

@faker-js/faker reorganized the API into logical, hierarchical modules based on real-world domains:

  • person (replaces name): firstName(), lastName(), jobTitle()
  • location (replaces address): city(), streetAddress(), country()
  • phone: number(), imei()
  • internet: email(), userName(), protocol()

This makes discovery easier and reduces cognitive load.

// @faker-js/faker: clear, grouped APIs
import { faker } from '@faker-js/faker';

const user = {
  name: faker.person.fullName(),
  email: faker.internet.email(),
  address: faker.location.streetAddress(),
  job: faker.person.jobTitle()
};

In contrast, faker uses older, less intuitive groupings:

// faker: legacy API structure
import faker from 'faker';

const user = {
  name: faker.name.findName(), // confusing name
  email: faker.internet.email(),
  address: faker.address.streetAddress(),
  job: faker.name.jobTitle() // job-related method under 'name'?
};

While @faker-js/faker maintains backward compatibility via aliases in early versions, the recommended path is the new structured API.

🧪 TypeScript Support: Built-In vs Bolted-On

@faker-js/faker ships with first-class TypeScript definitions. Types are generated from the source and kept in sync, so autocomplete and type checking work out of the box.

// @faker-js/faker: full TypeScript support
import { faker } from '@faker-js/faker';

const email: string = faker.internet.email(); // ✅ Correctly typed

faker does not include types in the main package. You must install @types/faker separately, which often lags behind actual API changes and may not reflect deprecations or inconsistencies accurately.

// faker: requires external types
import faker from 'faker';
// Need: npm install --save-dev @types/faker

const email = faker.internet.email(); // Type comes from DefinitelyTyped

For teams using TypeScript — which is most professional frontend shops today — this built-in support reduces setup friction and improves reliability.

🌍 Internationalization: Locale Handling

Both libraries support multiple locales, but @faker-js/faker improves how you manage them.

In faker, locales are bundled together by default, bloating your bundle even if you only need English.

// faker: all locales loaded by default (bad for bundle size)
import faker from 'faker';
// Even if you only use en, fr and de code is included

@faker-js/faker uses ESM-friendly dynamic imports, so you only pull in the locales you actually use:

// @faker-js/faker: tree-shakable locales
import { faker } from '@faker-js/faker';
import { en, de } from '@faker-js/faker/locale';

const enFaker = faker({ locale: en });
const deFaker = faker({ locale: de });
// Unused locales (like 'fr') are excluded from the final bundle

This matters a lot in frontend apps where every kilobyte counts.

🧩 Seeding and Reproducibility

Both support seeding for deterministic output — crucial for reliable tests.

faker seeds the global instance:

// faker: global seed
import faker from 'faker';
faker.seed(456);
console.log(faker.name.firstName()); // Always 'John' (for example)

@faker-js/faker allows per-instance seeding, which is safer:

// @faker-js/faker: instance-level seed
import { faker } from '@faker-js/faker';

const stableFaker = faker();
stableFaker.seed(456);
console.log(stableFaker.person.firstName()); // Always 'John'

// Other faker instances remain unaffected

This prevents accidental cross-contamination in test suites or multi-tenant mocking scenarios.

📦 Migration Path

If you’re stuck on faker, migrating to @faker-js/faker is straightforward but not automatic. Key steps:

  1. Replace import faker from 'faker' with import { faker } from '@faker-js/faker'
  2. Update method calls (e.g., faker.name.findName()faker.person.fullName())
  3. Handle seeding per instance instead of globally
  4. Import only needed locales

The official docs include a migration guide with detailed examples.

✅ Summary: What Should You Do?

Concernfaker@faker-js/faker
Maintenance❌ Deprecated✅ Actively maintained
Architecture❌ Global singleton✅ Isolated instances
TypeScript❌ Requires @types/faker✅ Built-in types
Bundle Size❌ All locales bundled✅ Tree-shakable locales
API Clarity❌ Inconsistent grouping✅ Logical, domain-based modules
Test Safety❌ Shared state risks✅ Predictable, isolated behavior

💡 Final Recommendation

Use @faker-js/faker — without hesitation — for any new or ongoing project. It’s not just “the new version”; it’s a thoughtful redesign that addresses real pain points developers faced with the original. The deprecated faker package should only exist in legacy codebases you plan to migrate away from.

Investing 30 minutes to adopt @faker-js/faker today saves hours of debugging, bundle bloat, and test instability down the road. In modern frontend engineering, that’s not just a good choice — it’s the only responsible one.

如何选择: @faker-js/faker vs faker

  • @faker-js/faker:

    Choose @faker-js/faker for new projects. It is the actively maintained successor to the original faker package, with regular updates, TypeScript support out of the box, a modular architecture that enables tree-shaking, and a cleaner, more consistent API. It’s the right choice if you need reliability, type safety, and modern tooling compatibility.

  • faker:

    Do not choose faker for new projects. The package has been officially deprecated by its maintainers, as noted on its npm page and GitHub repository. While it still works, it receives no updates, lacks TypeScript definitions in the core package, and uses a global singleton pattern that complicates testing and bundling. Only consider it if you’re maintaining legacy code that hasn’t been migrated.

@faker-js/faker的README

Faker

Generate massive amounts of fake (but realistic) data for testing and development.

npm version npm downloads Continuous Integration codecov Chat on Discord Open Collective sponsor

⚡️ Try it Online

Open in StackBlitz

📙 API Documentation

🚀 Features

  • 🧍 Person - Generate Names, Genders, Bios, Job titles, and more.
  • 📍 Location - Generate Addresses, Zip Codes, Street Names, States, and Countries!
  • ⏰ Date - Past, present, future, recent, soon... whenever!
  • 💸 Finance - Create stubbed out Account Details, Transactions, and Crypto Addresses.
  • 👠 Commerce - Generate Prices, Product Names, Adjectives, and Descriptions.
  • 👾 Hacker - “Try to reboot the SQL bus, maybe it will bypass the virtual application!”
  • 🔢 Number and String - Of course, we can also generate random numbers and strings.
  • 🌏 Localization - Pick from over 70 locales to generate realistic looking Names, Addresses, and Phone Numbers.

Note: Faker tries to generate realistic data and not obvious fake data. The generated names, addresses, emails, phone numbers, and/or other data might be coincidentally valid information. Please do not send any of your messages/calls to them from your test setup.

📦 Install

npm install --save-dev @faker-js/faker

🪄 Usage

// ESM
import { faker } from '@faker-js/faker';

// CJS
const { faker } = require('@faker-js/faker');

export function createRandomUser() {
  return {
    userId: faker.string.uuid(),
    username: faker.internet.username(),
    email: faker.internet.email(),
    avatar: faker.image.avatar(),
    password: faker.internet.password(),
    birthdate: faker.date.birthdate(),
    registeredAt: faker.date.past(),
  };
}

export const users = faker.helpers.multiple(createRandomUser, {
  count: 5,
});

💎 Modules

An in-depth overview of the API methods is available in the documentation for v10 (stable) and v10.* (next).

Templates

Faker contains a generator method faker.helpers.fake for combining faker API methods using a mustache string format.

console.log(
  faker.helpers.fake(
    'Hello {{person.prefix}} {{person.lastName}}, how are you today?'
  )
);

🌏 Localization

Faker has support for multiple locales.

The main faker instance uses the English locale. But you can also import instances using other locales.

// ESM
import { fakerDE as faker } from '@faker-js/faker';

// CJS
const { fakerDE: faker } = require('@faker-js/faker');

See our documentation for a list of provided languages.

Please note: Not every locale provides data for every module. In our pre-made faker instances, we fall back to English in such a case as this is the most complete and most commonly used language. If you don't want that or prefer a different fallback, you can also build your own instances.

import { de, de_CH, Faker } from '@faker-js/faker';

export const faker = new Faker({
  locale: [de_CH, de],
});

⚙️ Setting a randomness seed

If you want consistent results, you can set your own seed. If you are using faker.date methods, there are additional considerations. See Reproducible Results.

faker.seed(123);

const firstRandom = faker.number.int();

// Setting the seed again resets the sequence.
faker.seed(123);

const secondRandom = faker.number.int();

console.log(firstRandom === secondRandom);

🤝 Sponsors

Faker is an MIT-licensed open source project with its ongoing development made possible entirely by the support of these awesome backers

Sponsors

Backers

✨ Contributing

Please make sure to read the Contributing Guide before making a pull request.

📘 Credits

Thanks to all the people who already contributed to Faker!

The fakerjs.dev website is generously hosted by Netlify, with search functionality powered by Algolia.

📝 Changelog

Detailed changes for each release are documented in the release notes.

📜 What happened to the original faker.js?

Read the team update (January 14th, 2022).

🔑 License

MIT