How to create morse code translator

Published at Feb 16, 2024Updated at Feb 16, 20247  minutes read

Did you know what is morse code? It is a method of communication using short and long signals that are common represented as dots and dashes. Developed to transmit human language to math language and as only translate letters it became and international standard.

Short Answer

To create a morse code encrypter and decrypter you have two methods. One can use the ASCII table as described in this answer of Stackoverflow. But my preferred way is making a dictionary mapping all valid characters, which would be letters A from Z, number 0 to 9 and a blank space to separate words, anything else would be undefined and you can handle as you want.

  1. Create a dictionary containing all valid characters:
typescriptconst dictionary = {
  'a': '.-', 'b': '-...', 'c': '-.-.', 'd': '-..', 'e': '.', 'f': '..-.', 'g': '--.', 'h': '....',  'i': '..', 'j': '.---', 'k': '-.-', 'l': '.-..', 'm': '--', 'n': '-.', 'o': '---', 'p': '.--.', 'q': '--.-', 'r': '.-.', 's': '...', 't': '-', 'u': '..-', 'v': '...-', 'w': '.--', 'x': '-..-', 'y': '-.--', 'z': '--..', '1': '.----', '2': '..---', '3': '...--', '4': '....-', '5': '.....', '6': '-....', '7': '--...', '8': '---..', '9': '----.', '0': '-----', ' ': '/'
}
  1. Add function to transform letters into morse code:
typescript  function transformToMorse(rawText: string) {
    return rawText.split('').map(letter => dictionary[letter.toLowerCase()]).join(' ')
  }

Long Answer

What is morse code?

Morse code was created by Samuel Morse and Alfred Vail. It is a method to encode human words characters into just short and long sequences that can be anything from lights, sounds, smoke, anything you can make a short or long signal can be used to represent any word or number from a-z and 0-9. It became very popular in telegraph - grandfather of communication that used morse code to transmit messages from short and long bip. They even had a profession to people hearing and translating the messages- telegraphist.

Morse code works by using a sequence of short or long signal to represent one letter/number. For example, the letter t can be represent by a long signal -, but the letter g is two long signal and one short signal --.. With this you can make a very good system of communication to transform human language into natural language.

It's also very popular on pop culture as almost every riddle movie has a part using morse to encrypt or decrypt some kind of message.

Alphabet

CharacterMorse Equivalent
0-----
1.----
2..---
3...--
4....-
5.....
6-....
7--...
8---..
9----.
a.-
b-...
c-.-.
d-..
e.
f..-.
g--.
h....
i..
j.---
k-.-
l.-..
m--
n-.
o---
p.--.
q--.-
r.-.
s...
t-
u..-
v...-
w.--
x-..-
y-.--
z--..

Google learn morse

If you stay curious to learn more about morse code, I highly recommend you try Google's morse learn. They use images to help us remember the letters.

List of all codes cues used in morse typing trainer
Code cues used in the Morse Typing Trainer. Ref.https://kpronline.com/blog/learn-morse-code-with-the-morse-typing-trainer

Javascript/Typescript functions

To create a morse code encrypter and decrypter you have two methods.

  • Using ASCII table You can use the ASCII table as described in this answer of Stackoverflow. By knowing that ASCII table characters a - z goes from 97 to 122 and numbers 0 - 9 goes from 48 to 57 you can do something like this.
  1. First create 2 arrays containing the characters and one constant for the space.
typescript// Characters in order A - Z and 0 - 9
  const charactersAZ = ['.-', '-...','-.-.','-..','.','..-.','--.','....','..','.---','-.-','.-..','--','-.','---','.--.','--.-','.-.','...','-','..-','...-','.--','-..-','-.--','--..']
  const numbers09 = ['-----', '.----', '..---', '...--', '....-', '.....', '-....', '--...', '---..', '----.']
  const characterSpace = '/'
  1. Now you need to remove all weird characters that does not have an index on our arrays
typescript  function cleanRawText(rawText: string) {
    return rawText.toLowerCase().replace(/[^a-z0-9\s]/g, "");
  }
  1. Finally make a function to return the encrypted character.
typescript  const isNumberRegex = /^\d+$/
 
function transformToMorse(rawText: string) {
  const formatText = cleanRawText(rawText);
  return formatText.split('').map(letter => {
    if(letter === " ") return characterSpace;
 
    asciiCode = letter.charCodeAt(letter);
    if(isNumberRegex.test(letter)) return numbers09[asciiCode - 48];
    else return charactersAZ[asciiCode - 97];
  }).join(' ');
}
  1. Test the functions
typescript  transformToMorse('Hello world')
  // result .... . .-.. .-.. --- / .-- --- .-. .-.. -..

-Using dictionary

My preferred way is making a dictionary mapping all valid characters, which would be letters A from Z, number 0 to 9 and a blank space to separate words, anything else would be undefined and you can handle as you want.

  1. Create a dictionary containing all valid characters:
typescript  const dictionary = {
    'a': '.-', 'b': '-...', 'c': '-.-.', 'd': '-..', 'e': '.', 'f': '..-.', 'g': '--.', 'h': '....',  'i': '..', 'j': '.---', 'k': '-.-', 'l': '.-..', 'm': '--', 'n': '-.', 'o': '---', 'p': '.--.', 'q': '--.-', 'r': '.-.', 's': '...', 't': '-', 'u': '..-', 'v': '...-', 'w': '.--', 'x': '-..-', 'y': '-.--', 'z': '--..', '0': '-----', '1': '.----', '2': '..---', '3': '...--', '4': '....-', '5': '.....', '6': '-....', '7': '--...', '8': '---..', '9': '----.', ' ': '/'
  }
  1. Add function to transform letters into morse code:
typescript  function transformToMorse(rawText: string) {
    return rawText.split('').map(letter => dictionary[letter.toLowerCase()]).join(' ')
  }
  1. Test it
typescript  transformToMorse('Hello world')
  // result .... . .-.. .-.. --- / .-- --- .-. .-.. -..

Which one of them should I choose? Well, I think is up to you, personally I will not go to performance side because both has map method and the others doesn't make that much difference. I would choose based on readability as the first one the arrays seems a bit confusing and object making a dictionary seems much more readable for me.

Okay, but this is only an encrypter, where is the decrypter? For this, just invert the logic, make a dictionary containing morse code as keys, letters with values and the backslash for white space.

Bonus: UI - NextJS - Tailwind

This article only shows how to convert, but not how to create an application with these logics. I'am gonna leave this for you to create a design. I personally recommend to create a NextJS project with TailwindCSS for styling and Vercel as free host.

You can checkout the source code to get inspired

Home page of morse secret scripter containing input and output text areas for encrypt and decrypt
Morse secret scripter home page. Ref.https://morse-secret-scripter.felipescherer.com

Conclusion

In this article you learnt the history of morse code and how to create simple functions to translate/encrypt/decrypt morse code using Javascript/Typescript. Feel free to leave any suggestions, corrections and tips. Thank you for reading and see you in the next article. Have a nice day. 😎✨✨✨😎

About the author

Profile of Felipe Scherer
Written by:

Felipe Scherer

- Software Engineer

Hello. I currently working as developer for more than 2 years coding sites, apps and games. In the free time I like to write articles to help people get started in this incredible world of coding. Feel free to explore my Github and use my public code 😊. Don't forget to follow me on my socials. 🌟

Share this Article

Help us improve

If you find any mistakes or just want to make the article more complete, consider editing this page in Github.

edit_squareEdit on Github
open_in_new
descriptionContribution guide
open_in_new

You may also like

Primitive data types in JavaScript

Primitive data types in JavaScript

In every programming language you will find some primitives values. It's not different in JavaScript, we have 7- number, string, boolean, bigint, null, undefined and symbol. Every one having a different case usage. In this article I gonna show you every Javascript primitive values and its usage case, but first what is a primitive value? ## Definition In Javascript, a data type is considered primitive value if immutable and is not an object and has no methods or properties. You can never change a primitive value in Javascript, for example: ```js let a = 'hello' let b = a console.log(b) // "hello" b.substring(2) // "llo" console.log(b) // "hello" console.log(a) // "hello" let c = [3] let d = c c.push(1) console.log(c) // Array [ 3, 1 ] console.log(d) // Array [ 3, 1 ] ``` In the example above, we can never change the primitive value string *hello* no matter how many methods we do in *b*, but is not the case of array *c* and *d*, when we push item to *d*, automatically pushes to *c* too, so is mutable. Primitives values are super important to know, independently of the language used, every one has a critical importance and usage case. For this reason, we're gonna explain each one that exists in JavaScript. ## type number In JavaScript, **Number** is a primitive data type used to represent numerical values. It stores 64-bit floating-point numbers following the IEEE 754 standard, which supports double-precision. This makes it versatile for handling integers as well as decimals, and it's the primary type for representing numbers in JavaScript. Number accepts almost all operators. An interesting fact is that JavaScript handles somethings that would be consider error in other programming languages, we will see more in the next topics. An important aspect of numbers in JavaScript is that when you perform an operation that is not possible, such attempting invalid operations between types (like multiplying strings), the result will be *NaN*, which stands for 'Not a Number' and indicates an error in the computation. ```js const n = 1 const n2 = 2 console.log(n + n2) // 3 console.log(n - n2) // -1 console.log(n * n2) // 2 console.log(n / n2) // 0.5 console.log(n % n2) // 1 console.log(n === n2) // false console.log('text' * 'text') // NaN ``` ## type string A **String** is a sequence of characters used to represent text in JavaScript. It allows for the storage and manipulation of textual data, making it essential for handling words, sentences, and other character-based information. Strings have a wide range of use cases due to their versatility in representing and manipulating text, making them one of the most frequently used data types in JavaScript. JavaScript has a particularly behavior- If you use the sum operator with some string there will be no error as would happen in other programming languages, instead JavaScript handle this by transforming the result in a string by concatenating the values. ```js const s = '1' const s2 = 'text' console.log(1 + s) // 11 console.log(false + s2) // falsetext ``` ## bigint **BigInt** is used to store integers beyond JavaScript's safe integer limit (Number.MAX_SAFE_INTEGER). While powerful for handling very large numbers, it is rarely needed in typical small-medium applications. ```js const maxSafeNumber = Number.MAX_SAFE_INTEGER // 9007199254740991 const beyondMaxN1 = maxSafeNumber + 1 // 9007199254740992 const beyondMaxN2 = maxSafeNumber + 2 // 9007199254740992 const bigN = 9007199254740991n const beyondMaxBigN = 9007199254740991n + 2n // 9007199254740993n ``` ## boolean A **Boolean** is a logical data type that can only hold one of two values: *true* or *false*. It is commonly used in conditions and decision-making statements. Those values can be represented in other forms like binary, 1 represents true and 0 represents false. This means that, in Javascript you can make operations with those values. ```js const isDeveloper = true const isLastType = false console.log(true + 2) // 3 console.log(true - 2) // -1 ``` ## undefined **undefined** is a default value automatically assigned to variables that have been declared but not yet given a value, or to function parameters that have no corresponding arguments. ```js let value const value2 = undefined ``` ## symbol A **Symbol** is a unique and immutable primitive value that can be used as a key for properties in an object, ensuring property names do not conflict. ```js const sym1 = Symbol() const sym2 = Symbol('desc') const sym3 = Symbol('desc') console.log(sym2 === sym3) // false ``` ## null A **null** value represents a reference that intentionally points to a nonexistent or invalid object or address, indicating the absence of any value. In operations, you can treat null as 0 since many calculations can be performed by substituting null with 0 without affecting the outcome. ```js const value = null console.log(2 + null) // 2 console.log(2 * null) // 2 ``` ## Conclusion In this article we saw all the primitive data types that exists in JavaScript. This article was short, but I hope you like it. Have a nice day. 😎✨✨✨😎

12 must have VSCode extensions

12 must have VSCode extensions

VSCode is one of the most popular IDE's for coding everything from Java to Javascript. VSCode is super customizable and for that the community created a lot of custom extensions for VSCode. That's what we will cover in this article. ## Extensions.json This is a file you can add to `.vscode` folder and configure a set of extensions that are recommended by VSCode if the user don't have them. ## 1. VSCode Eslint <Img src="https://github.com/fescherer/blog/assets/62115215/be8bd7f5-b4f1-40c7-9974-290068604da3" name="VSCode Eslint" alt="Print showing VSCode Eslint extension" /> [As the doc says](https://eslint.org/docs/latest/use/getting-started): <Blockquote cite="https://eslint.org/docs/latest/use/getting-started"> Eslint is a tool for identifying and reporting on patterns found in ECMAScript/JavaScript code </Blockquote> This means that its goal is to be a tool to enforce certain patterns that we can consider "Good practices" or just avoid errors and bad syntaxes. This is possible by using a big set of rules that are completely customizable, and with just one line you can turn on or off the rules that you prefer and of course there are a lot of custom rules made by the community that in addition to add more validation to Javascript, also makes an integration to other stuff you may have like [React](https://www.npmjs.com/package/eslint-plugin-React), [TailwindCSS](https://www.npmjs.com/package/eslint-plugin-tailwindcss), [Typescript](https://typescript-eslint.io) and many more. So Eslint is very good but why do I need the extension? Well, you can run `npx eslint .` every time to check if Eslint got any error or warning, but if you want something more fast and easy to do, and trust me, you do, [installing the extension](https://marketplace.visualstudio.com/items?itemName=dbaeumer.vscode-eslint) allows Eslint to run parallel while coding, ensuring that the error will be shown as you code. **Link for download**: [VSCode Eslint](https://marketplace.visualstudio.com/items?itemName=dbaeumer.vscode-eslint) ## 2. Git Lens <Img src="https://github.com/fescherer/blog/assets/62115215/5a918dda-768d-40ae-b1aa-7baf01632f11" name="Git Lens" alt="Print showing Git Lens extension" /> Have you ever code with a partner? A friend, co-worker or relative and found a line with a very serious bug and needed went to Github to found how made that line? Well, with Git Lens solves your problem by adding a little hint of who made the last update to that line and in how much time ago. I can tell you must be thinking. How this is so useful? For me, it can be handy to have, you may forgot the extension installed but at some time I can assure you will use. Not only for to know the person how did change the line, but also to know when was the last time that line was updated. I know Git Lens offers other uses, but for my necessities this is good enough. You can read more about it [here](https://www.gitkraken.com/gitlens). **Link for download**: [Git Lens](https://marketplace.visualstudio.com/items?itemName=eamodio.gitlens) ## 3. Editor Config <Img src="https://github.com/fescherer/blog/assets/62115215/433781d2-df06-44ee-a87c-0399dd640e7e" name="Editor Config" alt="Print showing Editor Config extension" /> [Editor config](https://editorconfig.org) is a set of configurations that can maintain consistent coding across multiple IDEs, the configurations are basically about indentations, file formats, charset, unix style new lines, etc. This extensions enables to overwrite vscode configurations with the ones set on `.editorconfig` file. I always like to config this file instead my vscode because this way I know the code will be more consistent across multiple IDEs. **Link for download**: [Editor Config](https://marketplace.visualstudio.com/items?itemName=EditorConfig.EditorConfig) ## 4. Print showing Code Snapshot extension <Img src="https://github.com/fescherer/blog/assets/62115215/9fe14a53-fdf7-4849-b417-7ad969150b72" name="Code Snapshot" alt="Print showing Code Snapshot extension" /> I confess that Code Snapshot is not a super must have extension, but it is really nice and works really well. It can take screenshots from your code in MacOS style for you to post anywhere you want, like in a social media. **Link for download**: [Code Snapshot](https://marketplace.visualstudio.com/items?itemName=robertz.code-snapshot) ## 5. VSCode Icons <Img src="https://github.com/fescherer/blog/assets/62115215/f310c814-9f83-4752-a1a6-d21c8e9be2e2" name="VSCode Icons" alt="Print showing VSCode Icons extension" /> This one has a lot of my opinion, but I really think you should have an extension to modify your icons. It help so much when finding that specific file, I always go for the icon first instead of the file extension or the name of it. **Link for download**: [VSCode Icons](https://marketplace.visualstudio.com/items?itemName=vscode-icons-team.vscode-icons) ## 6. Import Cost <Img src="https://github.com/fescherer/blog/assets/62115215/80b88259-d63e-4233-b75d-32881818b14b" name="Import Cost" alt="Print showing Import Cost extension" /> One of the most important thing we as developer need to understand is how our site can be found by search engines like Google or Bing, and one thing I see a lot is a very large [First Contentful Paint(FCP)](https://web.dev/fcp). This is basically the time when the first render of page ends and this is [crucial for user experience](https://web.dev/fcp/#what-is-a-good-fcp-score), a bad time may result in user leaving your page. One of the strategies to decrease FCP time is the only first load the necessary and after you can load the small pieces like an api call. And this can be achieved by removing all the big bundles inside your project. The [Import Cost extension](https://marketplace.visualstudio.com/items?itemName=wix.vscode-import-cost) helps you to do that by showing the bundle size of that lib and then you can or remove it or search for a lighter lib. **Link for download**: [Import Cost](https://marketplace.visualstudio.com/items?itemName=wix.vscode-import-cost) ## 7. Markdown All in One and MDX <Img src="https://github.com/fescherer/blog/assets/62115215/53dd13aa-8bef-4898-9604-45bf2d875d79" name="MDX extension" alt="Print showing MDX extension" /> <Img src="https://github.com/fescherer/blog/assets/62115215/61d48f6d-a3bb-419a-bc6b-f0952582bd7d" name="A markdown file" alt="Print showing markdown file" /> In this topic I will put two extensions because I know not everyone is a React developer and uses [MDX](https://marketplace.visualstudio.com/items?itemName=unifiedjs.vscode-mdx) files as I use, so it is more reasonable for these people use [Markdown All in One](https://marketplace.visualstudio.com/items?itemName=yzhang.markdown-all-in-one) that gives all the essential stuff to have a great time writing your files. For React developers I suggest using [MDX](https://mdxjs.com), a superset of Markdown allowing to use React component inside Markdown. It is super handful and as I see, MDX is becoming a popular way to write Markdown in [NextJS](https://nextjs.org/docs/app/building-your-application/configuring/mdx). You can even use [Content layer](https://contentlayer.dev/docs/sources/files/mdx-d747e46d) to type your Markdown, if that's not fantastic I don't know what is. **Link for download**: [Markdown All in One](https://marketplace.visualstudio.com/items?itemName=yzhang.markdown-all-in-one) **Link for download**: [MDX](https://marketplace.visualstudio.com/items?itemName=unifiedjs.vscode-mdx) ## 8. Code Spell Checker <Img src="https://github.com/fescherer/blog/assets/62115215/fd817aa8-e864-4a55-98a9-8844c359cd9e" name="Code Spell Checker" alt="Print showing Code Spell Checker extension" /> Again, if you write files Markdown or anything that will probably be useful to have a grammar corrector and this extension is just like that. **Link for download**: [Code Spell Checker](https://marketplace.visualstudio.com/items?itemName=streetsidesoftware.code-spell-checker) ## 9. Auto Rename Tag <Img src="https://github.com/fescherer/blog/assets/62115215/10594378-40dd-419a-8ff6-9c38c2ec95e0" name="Auto Rename Tag" alt="Print showing Auto Rename Tag extension" /> One of the most useful extension I use is Auto Rename Tag, this as the name says, when change the tag name, the matching one will be changed too. **Link for download**: [Auto Rename Tag](https://marketplace.visualstudio.com/items?itemName=formulahendry.auto-rename-tag) ## 10. Themes <Img src="https://github.com/fescherer/blog/assets/62115215/effc88d1-7a25-40a3-b2b4-2c5f02c1d93f" name="Dracula Theme" alt="Print showing Dracula Theme" /> In number 10 I will put a more vast collection of extensions used to change the VSCode appearance, of course I am talking about [themes](https://vscodethemes.com/). There are a lot and I mean A LOT of available themes that can change the most different aspects, but most likely the colors, you can find a more lighter, darker, greener, yellowish and many more themes. If you want a recommendation, I would certain suggest to use [Dracula Theme](https://marketplace.visualstudio.com/items?itemName=dracula-theme.theme-dracula), it is one of most famous themes out there with more than 5 million installs. The colors are great even for dark environments or bright environments. **Link for download**: [Dracula Theme](https://marketplace.visualstudio.com/items?itemName=dracula-theme.theme-dracula) ## 11. Extra ones Well, for last I would suggest you to install the extension useful for what you are using to code, like if you are using [TailwindCSS](https://tailwindcss.com), please use the [TailwindCSS extension](https://marketplace.visualstudio.com/items?itemName=bradlc.vscode-tailwindcss), and this can be applied to everything in your project, [Styled Components](https://marketplace.visualstudio.com/items?itemName=styled-components.vscode-styled-components) or even other language than Javascript like [Python](https://www.python.org) VSCode has the extension [Python for VSCode](https://marketplace.visualstudio.com/items?itemName=ms-python.python). So have a look what you have installed and search if has an extension that could help you. 😊 ## Conclusion Conclusion reading this article you were introduced to a set of VSCode extensions that can help improve your coding time and quality. All of that are free and can be downloaded from [Microsoft VSCode MarketPlace](https://marketplace.visualstudio.com). Thank you for reading and see you in the next article. Have a nice day. 😎✨✨✨😎

Create custom classes Tailwind

Create custom classes Tailwind

Tailwind CSS is a popular modern CSS framework known for its utility-first approach. Unlike component-based frameworks like Bootstrap, Tailwind provides a collection of low-level utility classes that you combine to achieve your desired styles. This approach offers greater flexibility and granular control over your styles. It also boasts excellent build optimizations, including generating only the classes used in your project. While Tailwind offers built-in customization options, this article explores various methods for creating custom classes, with a focus on maintaining a positive developer experience. ## Tailwind CSS: Beyond the Basics - Crafting Custom Classes Tailwind CSS has a lot of classes, but there is some time you find yourself the need to use a class that are not in the default package, so what you do? There are a lot of ways to create custom classes, described in [docs](https://tailwindcss.com/docs/adding-custom-styles). I am gonna go though all of them, but be aware my favorite is the last one- By creating a plugin, so if you want, just skip to here ## Arbitrary values-properties-variants Tailwind is built for really hard customization, and that’s so true, you can literaly create any class just combining some prefix or sufix and the compiler will generate for you the classes for build. So, Why we avoid this approach when dealing to customization? The answer is because this goes agains the reusability concept of Tailwind, and if you use more than one that that arbitrary value, I recommend to create a custom utility for it. <Img src="https://github.com/fescherer/fennec-tales-blog/assets/62115215/76b33e7a-bd3f-4940-aabd-e3232034fc7b" name="Arbitrary property Tailwind example" alt="code example of tailwind arbitrary using a color of background" /> <Img src="https://github.com/fescherer/fennec-tales-blog/assets/62115215/9994a2a8-a1df-4be8-813a-759d7ea15e64" name="Build file " alt="Build file showing the arbitrary property became other class" /> ## Customizing the theme If you want to change the properties already build in, like the font-size or color, it’s perfect and really easy to do just customizing the Tailwind theme file. <Img src="https://github.com/fescherer/fennec-tales-blog/assets/62115215/3fcdaf65-9624-4966-8ccd-49aa74daf8c1" name="tailwind.config.ts" alt="Creating a class my-blue in Tailwind file" /> <Img src="https://github.com/fescherer/fennec-tales-blog/assets/62115215/61559e23-be18-43ea-a0a5-04dc0fbca834" name="Code example" alt="Using the custom classes created in a div" /> <Img src="https://github.com/fescherer/fennec-tales-blog/assets/62115215/810e5dfc-70f1-4505-88df-bc1a25c8653d" name="Build file- This may looks weird, but is the same blue I configured, but just with some Tailwind optimization." alt="Build file showing that Tailwind handle better using theme" /> The problem is when you need to create a custom component class, like you repeat that same classes and that became redundant and hard to read. <Img src="https://github.com/fescherer/fennec-tales-blog/assets/62115215/5920d701-17f9-476e-8df4-c5c3024c4594" name="Example of reduntant classes" alt="File showing a lot of container with same classes" /> Isn’t better having just one class like `hello-world-container`? Yes. ## @layer and @apply directive There is a way to add custom classes using some Tailwind directives in CSS files. Like this: <Img src="https://github.com/fescherer/fennec-tales-blog/assets/62115215/53c6e419-42b5-472e-a321-1af95569e58b" name="Example of reduntant classes" alt="File showing a lot of container with same classes" /> You can literaly put any CSS valid property just like the way you would do in normal CSS, but noticed I put the classes inside some directives, why? Tailwind is composed by layers that can be overwritten, eg. You have a base style for your button but you want to change it’s color just in one component, to make that you will need to overwrite it, in normal CSS you will probably use !important, and trust me in my experience if you had use !important, probabily there is something wrong with your code. So use layers with wisdom. I recommend using: - [@layer base](https://tailwindcss.com/docs/adding-custom-styles#adding-base-styles) for tag styles, like I used in the example for tag `code`. - [@layer components](https://tailwindcss.com/docs/adding-custom-styles#adding-component-classes) for classes that has more than one style like the `hello-world-container` which has **display: flex;flex-direction:column;justify-content:center;background-color:purple;padding:1rem**. Most customization you will need is gonna be made here. - [@layer utilities](https://tailwindcss.com/docs/adding-custom-styles#adding-custom-utilities) is the highest priority, so use carefully. I recommend using just for one single property like **transparent:background-color:transparent**. This will mostly be used for classes that do not exist in default Tailwind. Well, so we learned about the @layer directive, but what is that @apply in the example? This is a way to use your Tailwind token in the styling file. For build does not matter if you use the **hello-world-container** or **hello-world-container-2**, both produces the same result, so @apply helps your code readbility. Using directives may seen the best way to create custom classes in Tailwind, but as I said in the beginning of the article, this is not my favorite way. I prefer much more creating a custom plugin. ## Why I do not like Tailwind directives like @layer and @apply Fist I need to say why I love the experience of working with Taiwlind insted other CSS framework similar like Bootstrap. Tailwind has been investing not just in optimizations and fast files, but in development experience too. Tailwind has a very nice VSCode plugin called [Tailwind Intellisense](https://tailwindcss.com/docs/editor-setup#intelli-sense-for-vs-code) I personally do not recommend you use Tailwind without this plugin. One thing it changes is when you hover a class, it shows what is that CSS equivalent, is literally required for me and I do not see me not using it. <Img src="https://github.com/fescherer/fennec-tales-blog/assets/62115215/9b5e1959-3c80-4589-867c-47b0fdf40e48" name="Tailwind VSCode Intellisense showcase" alt="Print showing when hovering the class has a popup showing CSS equivalent" /> You know, when you create custom classes, you need Tailwind Intellisense to recognize it, but I never found a way to make recognize directives like @layer. When creating custom classes like that, you do not have the hover preview :( This is unacceptable, specially because custom classes do not exist in Tailwind Docs, is the most important classes to have a register and a easy way to check the CSS equivalent. So going though Github Issues and making a lot of testing. I probably have the best solution to create custom classes in Tailwind. ## Create custom plugins As you can see there are a lot of ways to customize you styles in Tailwind, but there is superior way to customize and still get the Tailwind Intellisense working for us, it’s called 🪽 Plugins 🪽. What is and how we implement? <Blockquote cite="https://en.wikipedia.org/wiki/Plug-in_(computing)"> is a software component that adds a specific feature to an existing computer program </Blockquote> So in [Tailwind](https://tailwindcss.com/docs/plugins) is not diffent, plugins are a way to modify the base of Tailwind, you can do a lot of it, but in this article I just gonna show how you can use to create custom classes styles. Every Tailwind project has a **tailwind.config.js** or **tailwind.config.ts** which has all of Tailwind’s configuration, including the **theme** from earlier, but what we want is the **plugins** <Img src="https://github.com/fescherer/fennec-tales-blog/assets/62115215/27b51eae-d5a0-4c14-81cf-19c97aa76398" name="tailwind.config.ts" alt="tailwind.config.ts file" /> You will need to use a function from Tailwind called `plugin`. I highly recommend using Typescript, for its typing features, which helps a lot, but of course you can use Vanila Javascript too. <Img src="https://github.com/fescherer/fennec-tales-blog/assets/62115215/e42b46ba-2710-4575-81b4-6ad8e864e30f" name="Plugin function" alt="Plugin function" /> In it’s parameters you put what you want to create. For this article, we want a component, so we use the addComponent param. <Img src="https://github.com/fescherer/fennec-tales-blog/assets/62115215/bee18037-70d5-435f-810f-fa6876a62629" name="Plugin function add components" alt="Plugin function add components" /> Now just add the class name and the styles like CSS or (CSS Style Declation)[https://www.w3.org/TR/cssom/#the-cssstyledeclaration-interface] (backgroundColor insted background-color). <Img src="https://github.com/fescherer/fennec-tales-blog/assets/62115215/5a6db547-3f58-4eca-98ce-c5564885fbd6" name="Custom class made by plugin example" alt="Custom class made by plugin example" /> And there you go, now you have the hovering effec from Tailwind Intellisense :) <Img src="https://github.com/fescherer/fennec-tales-blog/assets/62115215/688da377-c59e-4cd2-ba24-b02499d4da25" name="Class in action" alt="Print showing when hovering the custom class made by plugin, showing the equivalent CSS" /> ## More dev experience Here's an additional tip to elevate your Tailwind development experience: consider using the [eslint-plugin-tailwindcss package](https://www.npmjs.com/package/eslint-plugin-tailwindcss). This ESLint plugin offers various features to help you write cleaner and more maintainable Tailwind code. ## Summary This article explored various methods for creating custom classes in Tailwind CSS, emphasizing the importance of a positive development experience. By leveraging Tailwind plugins, you can create custom styles while maintaining IntelliSense support and overall code clarity. This approach empowers you to extend Tailwind's capabilities while keeping your development workflow efficient and enjoyable. Thanks for reading see you in the next article, have a nice day 😊