Skip to content

vitest entrypoint fails: jest-styled-components/vitest uses require('vitest') which is ESM-only #458

Description

@esetnik

Bug Report

Version

jest-styled-components@7.3.1, vitest@4.1.0

Description

The new /vitest entrypoint added in 7.3.x cannot be imported in a Vitest project because it uses require('vitest'), but Vitest is ESM-only and throws an error when loaded via CJS require().

vitest/index.js:

const { expect, beforeEach } = require('vitest');  // ← causes the crash

Because the package has "type": "commonjs", Node resolves this to vitest/index.cjs, which is Vitest's own CJS shim that intentionally throws:

Error: Vitest cannot be imported in a CommonJS module using require(). Please use "import" instead.

Steps to Reproduce

  1. Install jest-styled-components@7.3.1 in a Vitest project
  2. Add import 'jest-styled-components/vitest' to your setup file
  3. Run vitest

Error

Error: Vitest cannot be imported in a CommonJS module using require(). Please use "import" instead.

  ❯ Object.<anonymous> node_modules/vitest/index.cjs:1:7
  ❯ node_modules/jest-styled-components/vitest/index.js:1:32

Workaround

Import the main package entry instead of /vitest. The src/index.js main entry uses typeof beforeEach / typeof expect guards on globals rather than require('vitest'), so it works correctly when Vitest's globals: true is set:

// Instead of: import 'jest-styled-components/vitest'
import 'jest-styled-components'

Suggested Fix

The /vitest entrypoint should use ESM import syntax rather than CJS require. Options:

  1. Add an exports field with an "import" condition pointing to an .mjs version of the entrypoint
  2. Convert vitest/index.js to ESM (.mjs extension or scoped "type": "module")
// vitest/index.mjs
import { expect, beforeEach } from 'vitest';
import toHaveStyleRule from '../src/toHaveStyleRule.js';
import styleSheetSerializer from '../src/styleSheetSerializer.js';
import { resetStyleSheet } from '../src/utils.js';

beforeEach(resetStyleSheet);
expect.addSnapshotSerializer(styleSheetSerializer);
expect.extend({ toHaveStyleRule });

export { styleSheetSerializer, resetStyleSheet };

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Fields

No fields configured for issues without a type.

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions