Sunday, February 16, 2025

TypeScript to JavaScript (Auto Compile)

Hello,

Now a days, typescript is more preferred to write client-side code. However, it needs to later convert into JavaScript to use in browser. Let's see, how-


  1. Create New Project >> "Empty Project (.Net Framework)"
  2. Go to Tools >> NuGet Package Manager >> Manage NuGet Packages for Solution >> Browse >> Node.js
  3. Install Node.js
  4. Copy Solution Path
  5. Open Command Prompt
  6. CD <Solution Path>
  7. Then Run "npm install --save @types/xrm"
  8. It will add node_modules in project
  9. Add "JavaScript JSON Configuration File". Rename it "tsconfig.json"
  10. Update tsconfig.json as below
  11. The highlighted folder must be created in your solution
  12. {
      "compileOnSave": true,
      "complierOptions": {
        "outDir": "scripts/js",
        "rootDir": "./scripts/ts",
        "alwaysStrict": false,
        "removeComments": false,
        "noImplicitAny": false,
        "noEmitOnError": true,
        "sourceMap": true,
        "target": "ES2021",
        "lib": [
          "dom",
          "ES2021"
        ],
        "typeRoots": [
          "node_modules/@types"
        ]
      },
      "include": [
        "./scripts/ts/**/*"
      ],
      "exclude": [
        "node_modules",
        "node_modules/*",
        "**/*.specs.ts",
        "**/helper.js"
      ]
    }
    
  13. Update package.json
  14. Author Name, Project Name/Description, File Names, Folder Names must be updated as per actual
  15. {
      "author": {
        "name": "Test Author"
      },
      "name": "Demo Project",
      "description": "Demo Project",
      "version": "1.0.0",
      "devDependencies": {
        "@types/node": "20.5.2",
        "types/xrm": "^9.0.80",
        "copyfiles": "^2.2.0",
        "del-cli": "^3.0.1",
        "typescript": "5.1.0-dev.20230423",
        "typings": "^2.1.1"
      },
      "scripts": {
        "build": "tsc -p tsconfig.json --build",
        "clean:all": "del-cli Scripts/TS/*.js && del-cli Scripts/TS/*.js.map",
        "copyfiles": "copyfiles Scripts/**/*.html Scripts/**/*.js Scripts/**/*.css dist"
      } 
    } 
  16. Check package-lock.json
  17. Update name if required
  18. It's done. Now test.
  19. Add new "TypeScript File" in TS folder. Rename it "firstfile.ts"
  20. Add below code:
  21. namespace Helper {
    
        export class Common {
            public static returnFullName(firstName: string, lastName: string): string {
                return firstName + " " + lastName;
            }
        }
    }
    
  22. Save the file. Typescript compiler will compile the file and create 2 files in JS folder
    1. firstfile.js
    2. firstfile.js.map