Alternative option for const enums in Typescript

In the ever-evolving world of Typescript transpilers, there is a noticeable shift towards per-module transpilation to boost build speed. However, this approach comes at a cost - it impedes cross-module const enum usage as type information is required for their transpilation.

I find myself dealing with a plethora of const enums which, without the inlining feature that const offers:

  1. Tend to balloon in size even after minification due to lengthy property names
  2. Reveal internal backend property names that should remain private

Currently, I generate these const enum definitions from backend native code. To provide an example, imagine being employed at Apple and having an extensive const enum encompassing every hardware device.

const enum HardwareType {
    Apple1 = 0,
    // ...
    iPhoneX = 412,
    // ...
    iPhoneUltraXD = 499, // Hypothetical unannounced iPhone
}

Simply switching const enum HardwareType to enum HardwareType, besides enlarging my bundle size, would inadvertently expose the new "iPhone Ultra XD" to the public.

Although tools like Terser offer support for --mangle-props, using it raises concerns mentioned in official documentation. Moreover, implementing a regex pattern to encompass every single HardwareType seems cumbersome. Bear in mind, the aforementioned scenario is just a glimpse; in reality, I have numerous enums with hundreds of values each.

While I strive to embrace cutting-edge technology for bundling applications, I can't help but wonder if there's a more efficient solution out there for compile-time inlining of constant values?

Answer №1

const enum may not be the most secure option for hiding original names, as the typescript compiler tends to add them in comments. An example can be seen in this playground.

// Input:
const enum Fruites {
    Apple = 1,
    Banana = 2
}

const x = Fruites.Apple
const y = Fruites.Banana

// Output:
"use strict";
const x = 1 /* Apple */;
const y = 2 /* Banana */;

If you're looking for a more reliable way to hide secret names in output files using the latest technology for application bundling, consider using esbuild-loader or esbuild. They offer a define option that allows you to replace secret naming with meaningless values at compilation time.

define: {
  "secrets.hardwareType.iPhoneUltraXD": "499"
}

You can then safely use the defined value in your source code.

// Source code: 
if (deviceId === secrets.hardwareType.iPhoneUltraXD) {
// Bundled code:
if(deviceId===499){

The define option can be configured in webpack or esbuild config files with any computed values, giving you flexibility in the number of compile-time definitions you can set.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Converting an HTML page to PDF with Angular using jsPdf and Html2Canvas

[1st img of pdf generated with position -182, 0, image 208,298 ][1]Converting an HTML page to PDF in Angular 8+ using jspdf and Html2canvas has been a challenge. Only half of the page is successfully converted into PDF due to a scaling issue. Printing th ...

Converting image bytes to base64 in React Native: A step-by-step guide

When requesting the product image from the backend, I want to show it to the user. The issue is: the API response contains a PNG image if the product has an image, but returns a (204 NO Content) if the product does not have an image. So, I need to display ...

Incorrect order in Angular2 NgFor within tree model when elements are removed and then added back

Currently experimenting with Angular 2 alpha version 44. Working with a tree model that utilizes recursion for display purposes. Each group contains 'Criterions', 'Segments', and other 'Groups'. Elements can be added or delet ...

Naming build files with specific names in vue-cli3

Currently, with vue-cli3, whenever I run npm run build -- --mode=production, it generates 2 css files and 2 js files. After making a code change, the names of the files also change to something like app.de90cdf7.js and chunk-vendors.a9204242.js each time. ...

Using masonry-layout with Next Js leads to a ReferenceError stating that window is not defined

Implementing the masonry-layout library by David Desandro in my Next app has been a smooth process. You can find the link here. When I apply it, the masonry layout functions perfectly as intended. Here's how I'm incorporating it successfully: imp ...

The string returned from the Controller is not recognized as a valid JSON object

When attempting to retrieve a string from a JSON response, I encounter an error: SyntaxError: Unexpected token c in JSON at position In the controller, a GUID is returned as a string from the database: [HttpPost("TransactionOrderId/{id}")] public asyn ...

Angular2 Error: TemplateRef provider missing in ng2-bootstrap

I've been attempting various solutions to address this issue, but unfortunately haven't been successful in resolving it: No provider for TemplateRef! Error log: EXCEPTION: Uncaught (in promise): Error: Error in ./FooterComponent class FooterC ...

The module './product' could not be located, resulting in error TS2307

app/product-detail.component.ts(2,22): error TS2307: Cannot find module './product'. I have tried several solutions but none of them seem to work for me. I am working on a demo app in Angular 2 and encountering this specific error. Any guidance ...

Service consuming in Angular 2 using Stomp protocol

Why am I seeing responseBody as undefined, but I am able to see the subscribe response in msg_body? What could be causing this issue with responseBody? let stomp_subscription = this._stompService.subscribe('/topic/queue'); stomp_subscription.ma ...

What are the best techniques for streamlining nested objects with Zod.js?

As a newcomer to zod.js, I have found that the DataSchema function is extremely helpful in verifying API data types and simplifying the API response easily. However, I'm curious if there is a way to streamline the data transformation process for myEx ...

Error in Angular Material: SassError - The CSS after "@include mat" is invalid. Expected 1 selector or at-rule, but found ".core();"

My Angular 11 project was running smoothly with Angular Material version 11 until I decided to update everything to Angular 12, including Material. However, after the update, the styles.scss file that comes with Material started throwing errors. The comple ...

Utilizing the dialogue feature within Angular 6

Situation: I am managing two sets of data in JSON format named customers and workers: customers: [ { "cusId": "01", "customerName": "Customer One", "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data- ...

Lazy loading implemented with BootstrapVue's b-nav component

Having some trouble wrapping my head around the following issue: I've created a Vue.js component with tabs that have routes. I opted for a variation of the b-nav Tabs style (official docs) and it's functioning well in terms of tabs and routing. ...

The HTTPS protocol seems to be causing CORS issues, but I can access http://localhost without

In my current project using TypeScript with Express, I encountered an issue with implementing CORS. In the past, I have successfully added CORS to regular Express.js projects without TypeScript and assumed it would work similarly. However, when making a ba ...

Using Angular to include a forward slash "/" in the text input for a date field

Hello everyone, I am a newcomer to AngularJS and I am looking to insert slashes in an input type text element. I prefer not to rely on external packages like angular-ui or input type Date. My goal is to have the format mm/dd/yyyy automatically applied as ...

Obtain a comprehensive list of React state fields

Is there a way to retrieve a list of state fields in a React component? I am looking for a way to access and work with the fields stored inside a React.Component state dynamically. In the code snippet below, there is a method called getStateFieldList(), w ...

Exploring deep nested components and elements in Angular for a targeted specific functionality

Is it possible to apply the ng deep css class to only one specific checkbox in my component, rather than all checkboxes? I want to customize just one checkbox and leave the others unchanged. How can this be achieved? Thank you. I need the CSS modificatio ...

Using TypeScript - Implementing a generic constraint to allow passing a Zod schema result as an argument to a function

I'm in the process of creating a custom controller function to streamline my application. The repetitive task of wrapping try-catch, parsing a zod schema, and merging the request zod schema into a single object is present in all handler functions. The ...

A step-by-step guide to integrating a legend on a leaflet map using Angular and the ngx-leaflet plugin

I am attempting to integrate a legend into a map generated using Asymmetrik/ngx-leaflet. The tutorial I followed for creating the map can be found at https://github.com/Asymmetrik/ngx-leaflet. There are two distinct layers on the map, each requiring its ow ...

Launch another modal and then deactivate the initial modal

Having two Modals has presented a challenge for me when it comes to closing the first modal after the second one is opened. I attempted a solution, but it prevented the second Modal from opening altogether. This code snippet below belongs to the first Mo ...