Skip to content

Commit

Permalink
Support default export and UMD (#301)
Browse files Browse the repository at this point in the history
It’s possible to support both a CJS export and a `.default` property by
defining the export as an interface that has a call expression and a
default property. This makes it possible to use
`import classNames from 'classnames'` or `classNames.default('')`.

Also this packages exposes a UMD module, meaning `classNames` is
available as a global when using a TypeScript script, but not when using
a TypeScript module. This is supported by adding
`export as namespace classNames`.
  • Loading branch information
remcohaszing authored Mar 27, 2023
1 parent 1e53727 commit d52250f
Show file tree
Hide file tree
Showing 4 changed files with 24 additions and 2 deletions.
10 changes: 9 additions & 1 deletion bind.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,14 @@ declare namespace classNames {
type Binding = Record<string, string>;
}

declare function classNames(this: classNames.Binding | undefined, ...args: ArgumentArray): string;
interface ClassNames {
(this: classNames.Binding | undefined, ...args: ArgumentArray): string;

default: ClassNames;
}

declare const classNames: ClassNames;

export as namespace classNames;

export = classNames;
3 changes: 3 additions & 0 deletions dedupe.d.ts
Original file line number Diff line number Diff line change
@@ -1,2 +1,5 @@
import classNames = require('./index.js');

export as namespace classNames;

export = classNames;
10 changes: 9 additions & 1 deletion index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,17 @@ declare namespace classNames {
type Argument = Value | Mapping | ArgumentArray;
}

interface ClassNames {
(...args: classNames.ArgumentArray): string;

default: ClassNames;
}

/**
* A simple JavaScript utility for conditionally joining classNames together.
*/
declare function classNames(...args: classNames.ArgumentArray): string;
declare const classNames: ClassNames;

export as namespace classNames;

export = classNames;
3 changes: 3 additions & 0 deletions tests/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import dedupe = require('classnames/dedupe');
import bind = require('classnames/bind');

// default
classNames.default('foo');
classNames('foo');
classNames(null);
classNames(undefined);
Expand Down Expand Up @@ -44,6 +45,7 @@ classNames({a: true}, 'b', 0);
classNames({}, Infinity, [{}, []]);

// dedupe
dedupe.default('foo');
dedupe('foo');
dedupe(null);
dedupe(undefined);
Expand All @@ -68,6 +70,7 @@ dedupe([Symbol()]);
dedupe([[Symbol()]]);

// bind
bind.default.bind({foo: 'bar'});
const bound = bind.bind({foo: 'bar'});
bind.bind(undefined);
// $ExpectError
Expand Down

0 comments on commit d52250f

Please sign in to comment.