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

Adding innerHTML content to tooltip title using typescript in an Angular project

I have encountered an issue while trying to display HTML content inside a tooltip element's title attribute. The HTML content is not rendering as expected and appears as text instead. Let me outline the structure of my Angular project: library.comp. ...

Initiate the Bull Queue Process upon launching the Application

As I develop my API, I am setting up a queue and adding jobs to it. Additionally, I have configured the API to start processing these jobs as soon as they are added. const newQueue = createQueue(queueName, opts); newQueue.add('JokesJob', data, o ...

Leveraging PHP variables to determine the image location, implement an onclick function to cycle through the image gallery

I am facing an issue with a database query that is supposed to display multiple images. These images are stored in a PHP variable and shown one at a time using a JavaScript gallery with an onclick function to navigate through them. Unfortunately, the funct ...

Tips for implementing and utilizing onclick functions in EJS

My goal is to develop a trivia game with interactive features. I aim to enable users to click on an answer, which will trigger a border effect and increase the points variable. Below is the layout of the entire page: <% include ../partials/boilerp ...

The declaration module in Typescript with and without a body

I am facing an issue with importing a .mdx file. When I include the following in my mdx.d.ts: /// <reference types="@mdx-js/loader" /> import { ComponentType } from "react"; declare module '*.mdx' { const Component: ...

A comprehensive guide to effectively formatting Recharts in React: addressing alignment and size management!

While attempting to style two graphs as floating cards, I am encountering difficulties in controlling the sizing and centering of the graphs. Specifically, I am having trouble with the pie chart in this example. To address this issue, I am passing paramete ...

io-ts: Defining mandatory and optional keys within an object using a literal union

I am currently in the process of defining a new codec using io-ts. Once completed, I want the structure to resemble the following: type General = unknown; type SupportedEnv = 'required' | 'optional' type Supported = { required: Gene ...

What could be causing the console to display undefined?

Can anyone help me with an issue I'm having while making an AJAX call using fetch and promises? I have successfully displayed the temperatures, but for some reason, the location is showing up as undefined. Here is the code snippet: function getWeat ...

Unraveling in jQuery

Struggling to properly handle the data being returned by JQuery from an API call. Currently encountering an error in the process. Is it possible to iterate through data using a JQuery loop like this? $.each(data.results, function (i, item) { // attemptin ...

Ways to simulate a function that is a part of an internal object

Is there a way to mock a method from an object within my UnderTest class? When the Update method is triggered by an event from a child component, I need to mock the service.saveNewElement(data) method in order to test data in the then() block. <script ...

REDUX: The dispatch function is failing to update the store

Working on a project developing a chrome extension that involves dispatching functions in popup.tsx. However, the store does not update when I try to dispatch. Interestingly, the same code works perfectly fine in the background page. Any suggestions on wha ...

Automate Zoom join function with the help of puppeteer

Having trouble joining a Zoom meeting using Puppeteer, my code is not capturing the password field. Can anyone assist? Here is my code snippet: const puppeteer = require("puppeteer-extra"); const StealthPlugin = require("puppeteer-extra-plu ...

Is there a way to establish a pre-defined key in a mat-table?

I am fetching data from an API and I need to display it in a key-value format on a mat table. The keys are predefined and not provided by the API. The data retrieved from the API is shown here: image1 I want to display it on a mat table like this: mat ta ...

Refreshing the page does not trigger Angular callHooks

Encountering an issue with the proper invocation of F5 button or directive call URL from the address bar resulting in ngOnInit not being triggered correctly. Using a debugger to analyze the situation, it was noticed that callHook is not initiated after ngO ...

JavaScript Slider for Color Selection

In my slider, I have added a .images class along with buttons for previous and next. To set the colors, I have used JavaScript to define an array like this: let colors = ['red', 'green',]; Currently, clicking the next-button displays ...

Is there a way to verify an email address and transfer form data to a different HTML page for printing?

How do I troubleshoot email validity checking issues in my form? It works fine when no characters are entered, but fails when characters are inputted. What could be causing this problem? Additionally, I want to open a new HTML sub-file after form submissi ...

Display the hover effect for the current card when the mouse is over it

When the mouse hovers over a card, I want only that specific card to show a hover effect. Currently, when I hover over any card, all of them show the hover effect. Is there a way to achieve this in Vue Nuxtjs? Here's what I am trying to accomplish: ...

Not all divs are triggering the hover event as expected

I am facing an issue while creating a webpage with overlapping background and content divs. The hover event works properly on the div with the class "content," but not on the div with the class "background." There is no interference with the event in the J ...

Is it possible to use getJSON to retrieve a value from an HTML tag ID that has already been displayed on a webpage? How about using json_decode

Is there a way to retrieve the value using the HTML tag ID after an HTML page has been rendered? For example, how can I access the date value using the td_date in my JavaScript function? Below is the code snippet that populates the data on the page: listS ...

Material-UI web application experiencing crashes due to worn-out cards, resulting in element type being declared as invalid and raising an error

After reviewing numerous similar SO questions, it appears that the issue always comes down to problems with imports. Typically, these involve mistyped import destinations or missing braces, but I have double-checked and found no such issues in my code. Th ...