A typescript transform that converts exported const enums into object literal.

Overview

ts-transformer-optimize-const-enum

CI Status codecov

A typescript transformer that convert exported const enum into object literal.

This is just like the one from @babel/preset-typescript with optimizeConstEnums: true but it works for typescript compiler.

This will transform exported const enum from

export const enum MyEnum {
  A,
  B,
  C,
  D = 10,
  E = C * 200,
}

into object literal like this

export const MyEnum = {
  A: 0,
  B: 1,
  C: 2,
  D: 10,
  E: 400,
} as const;

and it also strips const in declaration file, to make your code compatible with --isolatedModules

// my-enum.d.ts
declare enum MyEnum { A: 0, ... }

Why?

Const enum can only works in the same file. It works by inlining the exact value into code.

if (cond === MyEnum.A) { /*...*/ }

will compile to the following code. That's a great inline optimization.

if (cond === 0 /* A */) { /*...*/ }

However, const enums only work in the same file with isolateModules. Therefore, you can't use the exported const enum. The solution is to enable preserveConstEnums option to convert const enums to regular enums.

And the regular enum compiles to

export var MyEnum;
(function(MyEnum) {
  MyEnum[MyEnum['A'] = 0] = 'A';
  MyEnum[MyEnum['B'] = 1] = 'B';
  MyEnum[MyEnum['C'] = 2] = 'C';
  MyEnum[MyEnum['D'] = 10] = 'D';
  MyEnum[MyEnum['E'] = 400] = 'E';
})(MyEnum || (MyEnum = {}));

which is verbose. Not only can't you take advantage of enum inlining, but it also wastes a lot of bytes. That's the reason why this transform is made.

Although keys of object literals can't be tree-shaken by webpack, however, the exported object literals have no side effects like enums do. If one of your code-splitting chunks does not use it, it will be completely erased.

Installation

npm install ts-transformer-optimize-const-enum --save-dev

Usage

If you use vanilla TypeScript compiler, you can use this with ttypescript and compile with ttsc instead of tsc

ttypescript

// tsconfig.json
{
  "compilerOptions": {
    // ...
    "plugins": [
      { "transform": "ts-transformer-optimize-const-enum" },
      { "transform": "ts-transformer-optimize-const-enum", "afterDeclarations": true },
    ]
  },
  // ...
}

The afterDeclarations part is to strip out const keyword from declaration file.

webpack (with ts-loader or awesome-typescript-loader)

// webpack.config.js
const optimizeConstEnum = require('ts-transformer-optimize-const-enum').default;

module.exports = {
  // ...
  module: {
    rules: [
      {
        test: /\.ts$/,
        loader: 'ts-loader', // or 'awesome-typescript-loader'
        options: {
          getCustomTransformers: program => ({
            before: [
              optimizeConstEnum(program),
            ],
            afterDeclarations: [
              optimizeConstEnum(program),
            ],
          }),
        },
      },
    ],
  },
};

Rollup (with @rollup/plugin-typescript or rollup-plugin-typescript2)

// rollup.config.js
import typescript from '@rollup/plugin-typescript';
import optimizeConstEnum from 'ts-transformer-optimize-const-enum';

export default {
  // ...
  plugins: [
    typescript({
      transformers: [service => ({
        before: [
          optimizeConstEnum(service.getProgram()),
        ],
        afterDeclarations: [
          optimizeConstEnum(service.getProgram()),
        ],
      })],
    }),
  ],
};
You might also like...

The JavaScript library let’s you transform native tooltip’s into customizable overlays.

iTooltip The JavaScript library let’s you transform native tooltip’s into customizable overlays. Use: script src="/path/to/iTooltip.js"/script sc

Dec 17, 2021

Types generator will help user to create TS types from JSON. Just paste your single object JSON the Types generator will auto-generate the interfaces for you. You can give a name for the root object

Types generator will help user to create TS types from JSON. Just paste your single object JSON the Types generator will auto-generate the interfaces for you. You can give a name for the root object

Types generator Types generator is a utility tool that will help User to create TS Interfaces from JSON. All you have to do is paste your single objec

Dec 6, 2022

converts nuggies to usd and usd to nuggies for a variety of restaurant chains. Also includes a rest api. Built using NextJS and TypeScript

Prices All prices are currently based on the 4-piece from the respective chain or the equivalent lowest amount of nuggies. Plan is to add multiple pri

Jan 14, 2022

An automated tool help you to transform backend json data to TypeScript type.

ohmyts An automated tool help you to transform backend json data to TypeScript type. Quick Start Vite install npm i @ohmyts/vite -D 🤽 playground play

Sep 23, 2022

A utility that mutates and transforms a style-dictionary object into something Figma Tokens plugin understands

A utility that mutates and transforms a style-dictionary object into something Figma Tokens plugin understands

Brought to you by Style Dictionary To Figma A utility that transforms a style-dictionary object into something Figma Tokens plugin understands. Used b

Jan 4, 2023

A Plugin which converts .md Files from Obsidian to your Kindle

A Plugin which converts .md Files from Obsidian to your Kindle

Project 2: obsidian-kindle-export An Obsidian-Plugin which sends your Notes to your Kindle as .mobi File This is the exported .mobi File Introduction

Dec 26, 2022

Converts your IPv4 address to a 4x4 2-bit PNG which you can extract the IP from.

Converts your IPv4 address to a 4x4 2-bit PNG which you can extract the IP from.

IP-to-PNG Converts your IPv4 address to a 4x4 2-bit PNG which you can extract the IP from. https://www.npmjs.com/package/ip2png Run npm install ip2png

Nov 30, 2022

Command line tool that converts HTML to markdown.

@wcj/html-to-markdown HTML conversion tool to markdown. command line tool = @wcj/html-to-markdown-cli. Installation This package is ESM only: Node 14

Nov 6, 2022

Converts JSX to HTML strings at compile time.

unplugin-jsx-string Converts JSX to HTML strings at compile time. Installation npm i unplugin-jsx-string Vite // vite.config.ts import JsxString from

Sep 3, 2022
Comments
  • Feat/support export later

    Feat/support export later

    Support export not in the modifier of EnumDeclaration.

    Before this PR, only the following syntax work

    export const enum WorkingEnum { A }  // will be transformed
    

    After this PR, the following code works as well.

    const enum MyEnum1 { A } // will be transformed
    const enum MyEnum2 { A }  // will be transformed
    export { MyEnum1, MyEnum2 as AliasEnum }
    const enum AnotherEnum { A }  // will be transformed
    export default AnotherEnum
    const enum NotExportedEnum { A } // will not be transformed
    
    opened by Fonger 1
  • feat: support SourceMap mapping

    feat: support SourceMap mapping

    The source map doesn't map to generated object literal after transformed. We should update the source map range after transformation.

    Using this tool to analyze the output source map:

    You can see before this PR, there's no correct mapping from enum member to property assignment: image

    After this PR, the mapping works. image

    opened by Fonger 1
  • chore(deps): bump minimist from 1.2.5 to 1.2.6

    chore(deps): bump minimist from 1.2.5 to 1.2.6

    Bumps minimist from 1.2.5 to 1.2.6.

    Commits

    Dependabot compatibility score

    Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting @dependabot rebase.


    Dependabot commands and options

    You can trigger Dependabot actions by commenting on this PR:

    • @dependabot rebase will rebase this PR
    • @dependabot recreate will recreate this PR, overwriting any edits that have been made to it
    • @dependabot merge will merge this PR after your CI passes on it
    • @dependabot squash and merge will squash and merge this PR after your CI passes on it
    • @dependabot cancel merge will cancel a previously requested merge and block automerging
    • @dependabot reopen will reopen this PR if it is closed
    • @dependabot close will close this PR and stop Dependabot recreating it. You can achieve the same result by closing it manually
    • @dependabot ignore this major version will close this PR and stop Dependabot creating any more for this major version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this minor version will close this PR and stop Dependabot creating any more for this minor version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this dependency will close this PR and stop Dependabot creating any more for this dependency (unless you reopen the PR or upgrade to it yourself)
    • @dependabot use these labels will set the current labels as the default for future PRs for this repo and language
    • @dependabot use these reviewers will set the current reviewers as the default for future PRs for this repo and language
    • @dependabot use these assignees will set the current assignees as the default for future PRs for this repo and language
    • @dependabot use this milestone will set the current milestone as the default for future PRs for this repo and language

    You can disable automated security fix PRs for this repo from the Security Alerts page.

    dependencies 
    opened by dependabot[bot] 0
  • chore(deps): bump minimatch from 3.0.4 to 3.1.2

    chore(deps): bump minimatch from 3.0.4 to 3.1.2

    Bumps minimatch from 3.0.4 to 3.1.2.

    Commits

    Dependabot compatibility score

    Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting @dependabot rebase.


    Dependabot commands and options

    You can trigger Dependabot actions by commenting on this PR:

    • @dependabot rebase will rebase this PR
    • @dependabot recreate will recreate this PR, overwriting any edits that have been made to it
    • @dependabot merge will merge this PR after your CI passes on it
    • @dependabot squash and merge will squash and merge this PR after your CI passes on it
    • @dependabot cancel merge will cancel a previously requested merge and block automerging
    • @dependabot reopen will reopen this PR if it is closed
    • @dependabot close will close this PR and stop Dependabot recreating it. You can achieve the same result by closing it manually
    • @dependabot ignore this major version will close this PR and stop Dependabot creating any more for this major version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this minor version will close this PR and stop Dependabot creating any more for this minor version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this dependency will close this PR and stop Dependabot creating any more for this dependency (unless you reopen the PR or upgrade to it yourself)
    • @dependabot use these labels will set the current labels as the default for future PRs for this repo and language
    • @dependabot use these reviewers will set the current reviewers as the default for future PRs for this repo and language
    • @dependabot use these assignees will set the current assignees as the default for future PRs for this repo and language
    • @dependabot use this milestone will set the current milestone as the default for future PRs for this repo and language

    You can disable automated security fix PRs for this repo from the Security Alerts page.

    dependencies 
    opened by dependabot[bot] 1
Releases(v0.1.2)
Owner
Fonger
Web Developer / Reverse Engineer / IoT Enthusiast
Fonger
microregex is an open source and highly curated catalog of regular expression patterns. It offers programmers RegEx snippets that can be quickly exported into a variety of programming languages and distributed around teams.

microregex - A catalog of RegEx patterns View Demo · Report Bug · Request Feature Loved the tool? Please consider contributing ✍️ to help it improve!

Sunit Shirke 4 Oct 25, 2022
A TypeScript namespace declaration for KeyboardEvent.key strings, just in case your code is allergic to enums.

ts-key-namespace A TypeScript namespace declaration for KeyboardEvent.key strings, just in case you prefer namespaces to enums. Largely based on ts-ke

Daniel Soohan Park 3 Apr 5, 2022
A responsive JS that supports literal expression of HTML

WEBX 支持 View Model 混合书写 支持字面上声明模型绑定 其实这是个响应式的 JS ,只是额外支持了 HTML 的字面表达 和一般的 MV* 框架实现方式不太一样,WEBX 通过编译时语义分析转化将更改的响应最小化(不需要在运行时执行庞大的 VDOM 比对),更新效率大概是 VUE 的

null 21 Apr 26, 2022
JavaScript enums using proxies.

enum-xyz JavaScript enums using proxies. Based on this tweet Install $ npm install enum-xyz --save Usage Strings import Enum from 'enum-xyz' const {

Chase Fleming 38 Oct 22, 2022
Small TS library to type and safely handle `serde` JSON serializations of Rust enums.

rustie-ts TypeScript library with helper types and functions to type-safely handle Rust's serde JSON serialization of Enums. It can also be used stand

Kelvin Steiner Santos 4 Jul 17, 2022
Converts an iterable, iterable of Promises, or async iterable into a Promise of an Array.

iterate-all A utility function that converts any of these: Iterable<T> Iterable<Promise<T>> AsyncIterable<T> AsyncIterable<Promise<T>> Into this: Prom

Lily Scott 8 Jun 7, 2022
A generative engine that takes various png layers on a sprite sheet format, combines them and then converts them into a .gif file

Welcome to the Generative GIF Engine v2.0.4 ?? [8 minute read] This python and node app generates layered-based gifs to create NFT gif art! It is fast

Jalagar 112 Jan 2, 2023
A generative engine that takes various png layers on a sprite sheet format, combines them and then converts them into a .gif file

Welcome to the Generative Animated Engine v3.0.1 ?? [8 minute read] This repo used to be called jalagar/Generative_Gif_Engine but because it now suppo

Jalagar 47 May 24, 2022
Converts select multiple elements into dropdown menus with checkboxes

jquery-multi-select Converts <select multiple> elements into dropdown menus with a checkbox for each <option>. The original <select> element is hidden

mySociety 22 Dec 8, 2022
🍎Transform an SVG icon into multiple themes, and generate React icons,Vue icons,svg icons

IconPark English | 简体中文 Introduction IconPark gives access to more than 2000 high-quality icons, and introduces an interface for customizing your icon

Bytedance Inc. 6.8k Jan 5, 2023