What are the steps to showcase the content of a Typescript file on an HTML webpage?

We are looking to create a sample gallery with source code examples.

Including typescript, html, and HTML files to showcase similar to the Angular.io component samples pages.

Is there a way to extract the source code from a typescript file within our project directory and display it?

The Angular.io utilizes this component https://github.com/angular/angular/blob/main/aio/src/app/custom-elements/code/code-example.component.ts, but the build and rendering process seems overly complex...

- Eric

Answer №1

You can find code samples that are not necessarily part of your own codebase.

These examples serve as guides for using a library or something you have developed.

Therefore, it's advisable not to create a .ts file and load it as text. Instead:

  • Write the TypeScript content directly into your HTML
  • Declare a string containing the TypeScript code

If you prefer to have autocomplete for the TypeScript content:

  • Create a TS file in the assets folder to avoid it being built, and then load it through HttpClient

Answer №2

[...] how can we retrieve and display the source code of a TypeScript file that already exists in our project?

One way to achieve this is by utilizing the Fetch API, which allows for asynchronous fetching of files from the server.

Important Note: Working with the Fetch API involves initiating two asynchronous tasks:

  1. An operation to retrieve the file response asynchronously
  2. An operation to extract the content of the file from the file response asynchronously

Example:

const fetchAndDisplayTSFile = async () => {

  // FETCH THE FILE RESPONSE
  const tsFileResponse = await fetch('/path/to/your/typescript-file.ts');
 
  // EXTRACT THE FILE CONTENT AS TEXT
  const tsFileContent = await tsFileResponse.text();
    
  // CREATE A NEW <CODE> ELEMENT
  const codeElement = document.createElement('code');

  // INSERT THE FILE CONTENT INTO THE <CODE> ELEMENT
  codeElement.textContent = tsFileContent;

  // APPEND THE <CODE> ELEMENT TO THE DOCUMENT BODY
  document.body.append(codeElement);
}

fetchAndDisplayTSFile();

Further Reading:

Answer №3

Initially, my query was posted on this platform:

Looking for a solution: How to replace raw-loader while transitioning to Angular 12?

In our Angular 11 application, we used to include source code from the codebase in the following way:

html: require(!!raw-loader!./${files}.component.html)

or

ts: require(!!raw-loader!./${files}.component)

However, post migrating to Angular 12, the raw-loader functionality seems to have disappeared. I attempted using ?raw which worked for HTML files:

html: require(./${files}.component.html?raw)

But it didn't work for TypeScript files:

ts: require(./${files}.component?raw)

The double exclamation marks that were meant to prevent loaders are no longer effective. Any suggestions or solutions would be greatly appreciated.

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

What is the method for retrieving data from a node in Firebase Realtime Database using TypeScript cloud functions, without relying on the onCreate trigger?

Being a beginner with Firebase and TypeScript, I have been struggling to retrieve values from a reference other than the triggered value. Despite finding answers in JavaScript, I am working on writing functions using TypeScript for real-time database for A ...

Steps for deactivating an eventhandler while another is being triggered:

There are two event listeners attached to a single input field. One triggers on change, while the other activates when selecting an autocomplete suggestion from Google. The issue arises when interacting with an autocompletion option as both handlers execut ...

Passing Optional Parameters to AngularJS Modal

Is there a way to pass an optional parameter to my angularJS modal? Let's take a look at the code: TRIGGER CONTROLLER: $modal.open({ templateUrl: 'UploadPartial.html', controller: 'photos.uploadCtrl', resolve: { presele ...

The entire DOM in Angular2+ flickers upon loading a component using ngFor

I am facing an issue where, after a user clicks on an item to add it to a list and then renders the list using ngFor, there is a flickering effect on the screen/DOM. The strange thing is that this flicker only happens after adding the first item; subsequen ...

An error is encountered with the getToken function in the Edge Runtime when using dynamic code evaluation methods such as 'eval', 'new Function', or 'WebAssembly.compile'

Working on a project that utilizes NextAuth.JS for authentication and Redux-Saga as the state manager. To enable refresh token rotation, I have created the following set of functions: get-token.ts: import { UUID } from 'crypto'; import jwt from ...

In TypeScript, Firestore withConverter may return a QueryDocumentSnapshot instead of the expected Class object

I'm currently exploring the usage of Firestore's withConverted method in Typescript to retrieve queries as instances of my customized class. Custom EventConverter Class import Event from "@/models/Event"; class EventConverter implemen ...

Utilizing jQuery to submit the form

After clicking the search icon, it displays an alert with the message ok, but not h. Based on the code snippet below, it is intended to display alerts for both ok and h. <?php if(isset($_POST['search'])){ echo "<script type='text/ ...

Guidelines on how to retrieve information from an AJAX request in PHP

I am in the process of developing an application that involves calling a JS function in PHP like this: $data = "<script>JSFunction();</script>"; The JSFunction is defined as follows: function JSFunction(){ $.ajax({ type: 'POST' ...

Adding information to a single class that shares a common name

Currently, I have successfully implemented a row cloning scenario where multiple dynamic rows are created after confirming an inventory number from a MySQL database. However, I am facing an issue with inserting the inventory data only to the next DIV eleme ...

What is the method for retrieving the name of the currently selected HTML element?

After using jQuery to select certain tags, I am now trying to obtain the name of each tag: $('select, :checkbox, :radio').each(function(){ // ... }); To accomplish this, I have attempted the following code: $('select, :checkbox, :radio ...

What's the best way to update the value of an angular field upon submission?

Could someone please provide instructions on how to update the myName variable when the "submit" button is pressed? Thank you! app.js: app.controller('SomeController', ['$scope', 'emails', function($scope, emails) { emails ...

Creating reducers for a unique data type: A step-by-step guide

Today, I was working on enhancing a shopping website using React Typescript and Context API. My goal is to utilize React Reducers to manage the state of my Shopping Cart. I have custom Types defined for the Product type, which includes an Items Array and s ...

Exploring Angular 4.3's HTTP Interceptor Retry功能

As I delve into my first attempt at coding, I find myself faced with the challenge of capturing 401 errors using HttpInterceptor. My goal is to generate a new auth token based on a certain condition and then retry the process with that token in place. Howe ...

Dynamic mouse path

Currently, I am in the process of creating a mouse trail similar to what is found on this particular website. I have been using JavaScript, jQuery, and various libraries in my attempt to achieve this effect; however, it has proven to be more challenging th ...

What steps can be taken to prevent users from dragging a page horizontally?

One function on my site involves a horizontal scroll that animates the DIV to the left when a button is clicked. The element's width is set at 18000px, ensuring it has a horizontal scrollbar that I have since disabled. Despite this, users are still ...

How can we effectively create a table page object in Protractor that can handle various table selectors?

Recently, I have been delving into writing e2e tests in Protractor using page objects with JavaScript/Node.js. After reading numerous Stack Overflow posts and Julie's pages, as well as studying ProtractorPageObjects, I've come across an issue. A ...

Typing into the styled M-UI TextFields feels like a never-ending task when I use onChange to gather input field data in a React project

Having an issue where entering text into textfields is incredibly slow, taking around 2 seconds for each character to appear in the console. I attempted using React.memo and useCallback without success :/ Below is my code snippet: const [userData, setUserD ...

What is causing my basic angularjs to not function properly?

In my angularjs test instance, I am using a global variable but the alert tag is not functioning as expected. This code snippet is from my first example on codeschool. Any thoughts on why the alert is not running? <!DOCTYPE html> <html xmlns="ht ...

Having trouble with Onsen UI + React Navigator pushPage function?

After experimenting with the Onsen playground and React Combining Navigator and Tabbar example, I created this unique animation: I decided to reposition the button and input field for adding more users by using a fab. However, when I attempted to call nav ...

The submission of the Jquery form is not successful

I am struggling with a form on my page. I want to disable the submit button and display a custom message when submitted, then use jQuery to actually submit the form. <form> <input type="text" name="run"/> <input type=&quo ...