Simple Source Code Analysis of the classnames Package with 15k Stars

Comes with TypeScript implementation

Zachary Lee
Level Up Coding

--

Photo by YearOne on Unsplash

If you are developing web applications, you may have heard of the classnames npm package. It works with some front-end frameworks like React to allow you to compose and write CSS classes very easily. This article will explore how it works.

When learning an npm package, my habit is to use it first. Only by knowing how to use it can you better understand it. Its usage tutorial can be viewed in README.md, and the following are some examples extracted from it.

classNames('foo', 'bar'); // => 'foo bar'
classNames('foo', { bar: true }); // => 'foo bar'
classNames({ 'foo-bar': true }); // => 'foo-bar'
classNames({ 'foo-bar': false }); // => ''
classNames({ foo: true }, { bar: true }); // => 'foo bar'
classNames({ foo: true, bar: true }); // => 'foo bar'
// lots of arguments of various types
classNames('foo', { bar: true, duck: false }, 'baz', { quux: true }); // => 'foo bar baz quux'
// other falsy values are just ignored
classNames(null, false, 'bar', undefined, 0, 1, { baz: null }, ''); // => 'bar 1'

You can see that its API is very easy to use. Next, let’s take a look under the hood.

First, we need to look at its package.json, which describes some information about the npm package. To understand how it works, the most important fields are "main": "index.js", and "types": "./index.d.ts".

The main field represents the entry file of the npm package, and the types field represents the type definition under TypeScript runtime. In addition to that, it provides an alternate dedupe version and bind version (for CSS modules)

Next, let’s focus on index.js.

It’s the official forked version, I’ve added some comments. It can be seen that its logic is relatively simple, and some of its judgments have been considered very well today.

Here is the TypeScript version I made following its type definitions:

I used ES6 syntax and it also passed the classnames built-in test cases. Hope this helps you. Comments are welcome if you have any questions.

References

[1] https://github.com/JedWatson/classnames

Thanks for reading. If you like such stories and want to support me, please consider becoming a Medium member. It costs $5 per month and gives you unlimited access to Medium content. I’ll get a little commission if you sign up via my link.

Your support is very important to me — thank you.

--

--