Typescript implementation for a website featuring a single overarching file alongside separate files for each individual webpage

Although I've never ventured into the realm of Typescript before, I am intrigued by its concept of "stricter JS". My knowledge on the subject is currently very limited as I am just starting to experiment with it.

Essentially, I have developed my own set of functions for my website - a "core.js" file that is created by merging the files in "core/*.js". Each of these files defines properties on a global window.myLib object.

Subsequently, every page has its own JS file which manages specific events for that particular page and can access elements from the global window.myLib.

As a result, each page includes two script files:

<script src="/core.js"></script>
<script src="/js/page_name_here.js"></script>

This setup functions efficiently for me.

I utilize VSCode for development and have configured a "globals.d.ts" file listing the properties and functions defined within the library. This enables Intellisense to offer informative tooltips and hints regarding the content's location.

With a desire to advance further, I intend to transition completely to Typescript and have tsc compile my JS files.

The initial step involves compiling the library, presently executed on the PHP-side by examining file modification times, concatenating files when required, and sending the outcome to closure-compiler. Is this the correct approach for transitioning to TS?

window.myLib = {}
window.myLib.eventHandlers = require("./core/event-handlers.ts")
window.myLib.AJAX = require("./core/ajax.ts")
// ...

If not, what method is appropriate for compiling a file like this?

Following that, Step 2 entails handling the individual page files. I believe that since I already established the "globals.d.ts" file including definitions for the library functions, I don't need to undertake any special actions for enabling those files to leverage library functions. tsc should recognize the definitions and utilize them whenever window.myLib is referenced. Is my assumption accurate, or do I need to reference the core file in some manner?

Any additional guidance beyond these questions would be greatly appreciated. I am eager to embark on this new (to me) journey, though there appears to be quite a significant leap from simply writing JS and letting the browser interpret it to now programming for a compiler!

Answer №1

When it comes to transitioning from TypeScript to JavaScript in your development process, I highly recommend exploring the capabilities of Babel. It seamlessly integrates with the TypeScript compiler through its plugin system and can be easily incorporated into modern build tools like Webpack.

Caution: Setting up a comprehensive project using webpack with Babel and TypeScript can be time-consuming and overwhelming. You may reach a point where the complexity feels excessive, especially if your initial goal was simply to create a website using TypeScript.

Are you embarking on this project for educational purposes (where final output quality is not paramount) or aiming for a practical implementation with TypeScript? If it's the latter, consider exploring popular frontend frameworks that offer solutions for modularity and simplify the TypeScript experience.

You might want to explore:

  • NuxtJs, which is built on the more user-friendly Vue.js and also provides support for TypeScript.
  • Gatsbyjs, the React equivalent of NuxtJs. A TypeScript starter, eslint+prettier setup, and vscode config are available.
  • Svelte, known for its TypeScript compatibility and growing popularity as an alternative to React.
  • Explore other established web frameworks that embrace TypeScript. There are numerous options available, so consider leveraging existing frameworks rather than developing one from scratch to optimize productivity.

Each framework approaches modularity differently, but the underlying principle remains consistent:

  • Create small, modular functions with clear responsibilities and avoid implicit dependencies (e.g., reliance on global objects like window).
  • Utilize TypeScript's import syntax to incorporate these functions in your components wherever necessary.
  • Rely on the framework to handle tasks such as compilation, bundling, and code splitting – streamlining complex processes effortlessly.

TL;DR: For substantial projects, opting for a framework is advisable to enhance efficiency and functionality.

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

Creating a virtual roulette wheel with JavaScript

I'm currently working on creating a roulette wheel using JavaScript. While researching, I came across this example: , but I wasn't satisfied with the aesthetics. Considering that my roulette will only have a few options, I was thinking of using ...

Issue with Angular ngStyle toggle functionality not activating

I'm having an issue with toggling my navbar visibility on click of an image. It works the first time but not after that. Can anyone provide some assistance? Link to Code <img id="project-avatar" (click)="toggleNavbar()" width=20, height=20 style= ...

What is the best way to transfer values dynamically with C# code in jQuery?

Can anyone guide me on passing values dynamically in C# code using jQuery? I am currently working on a timepicker control application using jQuery in Visual Studio.NET. I have successfully passed values statically, but I'm unsure how to do it dynamic ...

AWS Lambda optimizes variable initialization by reusing values from previous executions, eliminating the need to reinitialize

Currently, I am encountering a problem while deploying an AWS Lambda Function for numeric calculations. The issue arises when the function is initially deployed and runs correctly, but subsequently it starts taking previous values into account and recalcul ...

Unable to alter fxFlex property within Component using "setAttribute('fxFlex', '25%')" does not function properly in Angular 6

Currently, I am utilizing the flexLayout module to create responsive divs in my Angular application. You can find more information about flexLayout at https://github.com/angular/flex-layout and also at https://alligator.io/angular/flex-layout/. const nav ...

The Angular Component utilizes the ng-template provided by its child component

I am currently facing an issue that involves the following code snippet in my HTML file: <form-section> <p>Hello</p> <form-section> <ng-template test-template> TEST </ng-template> ...

Unit testing for changes in AngularJS $scope variables within the .then() function

I'm currently facing an issue with unit testing a function in my controller. The problem lies in making a $scope variable testable. I am assigning the variable within the .then() block of my controller and need to ensure it is set correctly when the . ...

Using AngularJS to transfer data from a datepicker to an ng-model

I am currently trying to figure out how to pass the date from a datetimepicker into the model. Unfortunately, I am facing some challenges with this process. I wish I could provide a demo of the issue on a fiddle, but I am unsure of how to do so due to the ...

Error: Firebase has encountered a network AuthError, which could be due to a timeout, interrupted connection, or an unreachable host. Please try again later. (auth/network-request-failed

I have set up my Angular app to utilize Firebase's emulators by following the instructions provided in this helpful guide. In my app.module.ts, I made the necessary configurations as shown below: import { USE_EMULATOR as USE_AUTH_EMULATOR } from &apos ...

What is the best way to integrate the Telegram login widget into an Angular application?

Does anyone know how I can integrate the Telegram login widget into my Angular application without resorting to hacks? The required script is as follows: <script async src="https://telegram.org/js/telegram-widget.js?5" data-telegram-login="bot_name" ...

When incorporating a second overload as an object, it is generating a pair of errors

I'm currently working on creating an overload function that takes either two arguments or one argument as an object, which will be used in the following way: // Two parameters obj.set('a', '123'); obj.set('b', 'efg&a ...

Tips on how to prevent certain classes from being impacted by a hue-rotate filter applied to all elements on a webpage

I am currently in the process of adding a feature that allows users to choose between a dark or light theme, as well as select a specific theme color for the app. The implementation involves using CSS filters such as invert(1) for the dark theme and hue-ro ...

Mastering the art of Puppeteer with Javascript

I am currently learning how to make web requests using JavaScript with puppeteer. After some trial and error, I was able to extract the value of a tag from a random website. However, I am struggling to figure out how to retrieve 10 consecutive values of ...

Applying unique textures to individual sides in Three.js

Here is the code for my textured cube: const textureLoader: TextureLoader = new TextureLoader(); const textureArray: MeshBasicMaterial[] = [ new MeshBasicMaterial({ map: textureLoader.load("./model/front.jpeg") }), new MeshBasicMaterial({ map ...

A guide on updating the SQL order value through a select option using PHP and jQuery

To modify the arrangement of SQL data according to the chosen select option, I am looking to adjust the ORDER value. Within my action.php file, I retrieve values from the database and aim to incorporate a sorting select option that allows for changing the ...

Simple method for extracting data from JSON and saving it into an array with jQuery

I have a JSON file containing the resource "A" and literals "B", "C", and "D". My goal is to extract only the items B, C, and D, convert them into strings, and store them in an array. Below is the script I have written for this purpose: <script> // ...

Tips for extracting the y-coordinate from a touch event using d3

I am utilizing d3.js to display data in my Ionic app. I have a touch event that allows me to move a line and retrieve the coordinates where it intersects with my chart. While I can easily obtain the x-coordinate representing the date, I am struggling to ge ...

Creating Dynamic Graphs using Angular and Chart.js with Array Values

I have implemented ChartJS-2 to visualize a graph displaying an array of user activities, but it appears distorted: import { Component, OnInit, Input } from '@angular/core'; import { ChartOptions, ChartType, ChartDataSets } from 'chart.js ...

Integrate JavaScript date into the gulp-rev workflow

I have been encountering an issue while using the gulp-rev plugin to add a revision of my app/html page generated by the Yeomann webapp generator. My workflow involves zipping the app and then adding a revision, but I am having trouble replacing the hash t ...

Create an unordered Vue component object

In the data retrieved from the backend, there is an object containing various properties, one of which is the 'average' value. This object is ordered based on that value and when accessed through Postman, it appears as follows: ranking: ...