Generating Legible JavaScript Code from TypeScript

I am looking to maintain the readability of my compiled JS code, similar to how I originally wrote it, in order to make debugging easier. However, the typescript compiler introduces several changes that I would like to disable.

For instance:

During compilation, typescript modifies all import names as follows:

import AWS from 'aws-sdk' =>

const aws_sdk_1 = __importDefault(require("aws-sdk"));

instead of

const aws-sdk = require('aws-sdk')

Furthermore, it removes all line spacing that I had included for better readability and structure.

Is there a way to customize these settings?

tsconfig.json

{

  "compilerOptions": {
    /* Basic Options */
    // "incremental": true,                   /* Enable incremental compilation */
    "target": "es2017",
    /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019' or 'ESNEXT'. */
    "module": "commonjs",
    /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */
    // "lib": [],                             /* Specify library files to be included in the compilation. */
    "allowJs": true,
    /* Allow javascript files to be compiled. */
    "checkJs": true,
    /* Report errors in .js files. */
    // "jsx": "preserve",                     /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */
    // "declaration": true,                   /* Generates corresponding '.d.ts' file. */
    // "declarationMap": true,                /* Generates a sourcemap for each corresponding '.d.ts' file. */
    // "sourceMap": true,                     /* Generates corresponding '.map' file. */
    // "outFile": "./",                       /* Concatenate and emit output to single file. */
    "outDir": "./dist",
    /* Redirect output structure to the directory. */
    // "rootDir": "./",                       /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
    // "composite": true,                     /* Enable project compilation */
    // "tsBuildInfoFile": "./",               /* Specify file to store incremental compilation information */
    // "removeComments": true,                /* Do not emit comments to output. */
    // "noEmit": true,                        /* Do not emit outputs. */
    // "importHelpers": true,                 /* Import emit helpers from 'tslib'. */
    // "downlevelIteration": true,            /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
    // "isolatedModules": true,               /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */

    /* Strict Type-Checking Options */
    "strict": true,
    /* Enable all strict type-checking options. */
    // "noImplicitAny": true,                 /* Raise error on expressions and declarations with an implied 'any' type. */
    // "strictNullChecks": true,              /* Enable strict null checks. */
    // "strictFunctionTypes": true,           /* Enable strict checking of function types. */
    // "strictBindCallApply": true,           /* Enable strict 'bind', 'call', and 'apply' methods on functions. */
    // "strictPropertyInitialization": true,  /* Enable strict checking of property initialization in classes. */
    // "noImplicitThis": true,                /* Raise error on 'this' expressions with an implied 'any' type. */
    // "alwaysStrict": false,                  /* Parse in strict mode and emit "use strict" for each source file. */

    /* Additional Checks */
    // "noUnusedLocals": true,                /* Report errors on unused locals. */
    // "noUnusedParameters": true,            /* Report errors on unused parameters. */
    // "noImplicitReturns": true,             /* Report error when not all code paths in function return a value. */
    // "noFallthroughCasesInSwitch": true,    /* Report errors for fallthrough cases in switch statement. */

    /* Module Resolution Options */
    "moduleResolution": "node",
    /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
    // "baseUrl": "./",                       /* Base directory to resolve non-absolute module names. */
    // "paths": {},                           /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
    // "rootDirs": [],                        /* List of root folders whose combined content represents the structure of the project at runtime. */
    // "typeRoots": [],                       /* List of folders to include type definitions from. */
    // "types": [],                           /* Type declaration files to be included in compilation. */
    // "allowSyntheticDefaultImports": true,  /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
    "esModuleInterop": true,
    /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
    // "preserveSymlinks": true,              /* Do not resolve the real path of symlinks. */
    "allowUmdGlobalAccess": true,
    /* Allow accessing UMD globals from modules. */

    /* Source Map Options */
    // "sourceRoot": "",                      /* Specify the location where debugger should locate TypeScript files instead of source locations. */
    // "mapRoot": "",                         /* Specify the location where debugger should locate map files instead of generated locations. */
    // "inlineSourceMap": true,               /* Emit a single file with source maps instead of having a separate file. */
    // "inlineSources": true,                 /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */

    /* Experimental Options */
    "experimentalDecorators": true,
    /* Enables experimental support for ES7 decorators. */
    // "emitDecoratorMetadata": true,         /* Enables experimental support for emitting type metadata for decorators. */
  }
}

Answer №1

If you're struggling with debugging and need your JavaScript to be more readable, there's a solution using TypeScript. You can easily debug your TypeScript file in Chrome by running the following command:

node --inspect -r ts-node/register <your-ts-file.ts>

To use the above command, make sure you have ts-node installed first:

npm install --save ts-node

Answer №2

Preserving whitespace is not possible in this scenario. The TypeScript compiler undergoes processing based on the tsconfig settings, which may significantly alter the output and prohibits maintaining any formatting.

The resulting JavaScript will be influenced by your target and module system, particularly when it comes to imports. TypeScript aims to handle various scenarios comprehensively, even those that may seem unconventional. You can disable the __importDefault helper functions by setting

esModuleInterop: false

It's best to consider the generated JS as a binary file - a compiled output where the format is irrelevant. Just like you wouldn't scrutinize the contents of a DLL, there's no need to obsess over how the JavaScript looks. The only exception would be when transitioning away from TypeScript, in which case simply removing the TS annotations from the files would be more efficient than trying to customize the transpiled source code to match a specific layout.

When debugging, utilize source maps extensively. Focus on debugging your TypeScript code with these maps rather than dissecting the generated JavaScript.

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

Triggering a modal window with unique content by clicking on various images

Is there a way to trigger a modal window through clicking on an image? Additionally, can different images open different content upon clicking? I am planning to showcase a portfolio where clicking on an image will activate a modal that displays other image ...

Managing Nested Elements in State in ReactJS

Check out the code snippet below: import React,{useState} from 'react' const iState ={ Name : '', Email :'', Salary :0, Error:{ EName:'*', EEmail:'*', ESalary:'* ...

Here is a unique version of the text: "Utilizing Various MAT_DATE_FORMATS

I am facing an issue with multiple date input formats in a component. While most inputs follow the standard MM/DD/YYYY format, one requires a custom format (MM/YYYY). I found guidance here on how to customize the format but now all inputs are displaying wi ...

Choosing specific rows in a kogrid by clicking on a button within a column

My kogrid includes a single column with a view button for each row. I would like to show a popup containing the values of the selected row when the View button is clicked. How can I retrieve the values of the selected row in order to pass them into the p ...

Issue: When attempting to read the length of a property in Angular 6, a TypeError is being thrown because the property is

Unable to retrieve values from an array using the TS code below: this.dataservice.get("common/public/getAllCategories", null).subscribe(data => { //console.log('categories'+JSON.stringify( data)); this.categoriesarray = data; }); var ...

Keying objects based on the values of an array

Given the array: const arr = ['foo', 'bar', 'bax']; I am looking to create an object using the array entries: const obj = { foo: true, bar: true, bax: false, fax: true, // TypeScript should display an error here becau ...

Prolong the duration of a Facebook SDK access token to 60 days using C#!

How can I extend the 2-hour access token to a 60-day access token using the C# SDK? Can someone provide a sample code snippet for this specific section where the code has already been substituted with the 2-hour access token? Background: Despite trying va ...

Attempting to replicate the functionality of double buffering using JavaScript

In my HTML project, I have a complex element that resembles a calendar, with numerous nested divs. I need to refresh this view in the background whenever there are updates on the server. To achieve this, I set up an EventSource to check for data changes on ...

AngularJS restructured the homepage to function as a shell page instead of the traditional index page

As a newcomer to angularJS, I am learning that it is typically designed for Single Page Applications. Most example logins I come across define the index.html as the main page, with the ng-view portion contained within. However, in my situation, the Login ...

JavaScript 3D Arrays

Is there a way to create a 3D array similar to runes['red'][0]['test']? If so, how can I accomplish this? var runes = {} runes['red'] = [ 'test': ['loh'] ] runes['blue'] = {} runes[&apo ...

Having trouble with document.getElementById.innerHTML not displaying the correct content?

document.getElementById works in getting the element, but for some reason, the content disappears as soon as it is written in it. There are no errors on the console to indicate what's causing this behavior. I have been unable to identify the reason b ...

Tips for Extracting Real-Time Ice Status Information from an ArcGIS Online Mapping Tool

My goal is to extract ice condition data from a municipal website that employs an ArcGIS Online map for visualization. I want to automate this process for my personal use. While I have experience scraping static sites with Cheerio and Axios, tackling a sit ...

Enhance your Verold model object with engaging animations

Trying to utilize verold for animating 3D models through a script has been challenging. The proper usage of the verold API components seems unclear at the moment. A model has been successfully loaded into the scene with a script attached as an attribute o ...

Unexpected Behavior: using setTimeout in a ReactJS class component leads to incorrect value retrieval

App Component: class App extends React.Component { constructor() { super(); this.state = { user: 'Dan', }; } render() { return ( <React.Fragment> ...

I encounter obstacles when trying to execute various tasks through npm, such as downloading packages

Currently, I am facing an issue while trying to set up backend development using node.js on my personal computer. The problem lies with the npm command as it is not functioning correctly. Despite successfully installing a file without any errors, I am unab ...

When using the UI Router, nested views may display double slashes in the URL and redirect back to

I've been working on editing a project to incorporate a root view/state that encapsulates all other views/states within it. Previously, each page functioned as an independent state, making it cumbersome to implement global changes across all states wi ...

Is it considered acceptable to modify classes in a stateless React component by adding or removing them?

My stateless component functions as an accordion. When the container div is clicked, I toggle a couple of CSS classes on some child components. Is it acceptable to directly change the classes in the DOM, or should I convert this stateless component to a ...

Vue project encountering issue with displayed image being bound

I am facing an issue with a component that is supposed to display an image: <template> <div> <img :src="image" /> </div> </template> <script> export default { name: 'MyComponent', ...

What is the best way to retrieve text from the p tag and input it into the text field?

Looking to resolve a situation where two identical IDs exist and need to implement some JQuery. The objective is for the input value to automatically update itself based on changes in the text of the p tag. $(document).ready(function(){ ...

Leveraging personalized design elements from a theme in Material UI without the need for makeStyles

Is there a way to access the theme.customElements.actionButton in MyComponent without relying on makeStyles? For instance, can I directly use className={theme.customElements.actionButton}? theme.js const theme = createMuiTheme({ customElements: { ...