Ecosyste.ms: Awesome

An open API service indexing awesome lists of open source software.

Awesome Lists | Featured Topics | Projects

https://github.com/traffician/babel-plugin-objective-enums

Babel plugin supporting TypeScript-like enum syntax in JavaScript.
https://github.com/traffician/babel-plugin-objective-enums

babel-plugin enum enumerated-types javascript objective-enums

Last synced: about 2 months ago
JSON representation

Babel plugin supporting TypeScript-like enum syntax in JavaScript.

Awesome Lists containing this project

README

        

# babel-plugin-objective-enums

Babel plugin allowing to use enum syntax in JavaScript projects.
It wraps [objective-enums](https://github.com/Traffician/objective-enums) and it requires **Babel 7**.

Some code fragments are from [babel-plugin-transform-typescript](https://github.com/babel/babel/tree/master/packages/babel-plugin-transform-typescript).

## Installation

```sh
$ npm install --save-dev babel-plugin-objective-enums
```

## Usage

### Via `.babelrc` (Recommended)

**.babelrc**

```json
{
"plugins": ["babel-plugin-objective-enums"]
}
```

### Via CLI

```sh
$ babel --plugins babel-plugin-objective-enums script.js
```

### Via Node API

```javascript
require('babel-core').transform('code', {
plugins: ['babel-plugin-objective-enums']
});
```

## All-in-one Example
```typescript
enum Colors {
Red = '#FF0000',
Yellow = {r: 255, g: 255, b: 0},
Green = 0x008000,
Blue = true,
White,
Black = White * 50
}

// Get color value and name
console.log(Colors.Red.value + ' - ' + Colors.Red.toString()); // #FF0000 - Red

// Only green and blue are allowed colors
let allowed = Colors.Green | Colors.Blue;

// Get names of allowed colors
console.log(Colors.match(allowed)); // ["Green", "Blue"]

// Add yellow to allowed colors
allowed |= Colors.Yellow;
console.log(Colors.match(allowed)); // ["Green", "Blue", "Yellow"]

// Remove blue from allowed colors
allowed &= ~Colors.Blue;
console.log(Colors.match(allowed)); // ["Green", "Yellow"]

// Get common elements' names of allowed and selected colors
const selected = Colors.Red | Colors.Yellow | Colors.Black;
console.log(Colors.intersect(allowed, selectedColors)); // ["Yellow"]
```