Using Typescript to import HTML files into a string with Express

My current challenge involves importing an HTML file using

import template as "./template.html"
as a string to be displayed to the user through Express's res.end(template); function.

To facilitate this, I have set up an index.d.ts file in the main directory of my project with the following contents:

declare module '*.html' {
    const value: string;
    export default value;
}

Although I can import template.html successfully, I encounter an issue when running the program. The error message indicates:

/home/koen/Workspace/xyz/src/template.html:1
<!DOCTYPE html>
^

SyntaxError: Unexpected token <
    at Module._compile (internal/modules/cjs/loader.js:723:23)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)
    at Module.load (internal/modules/cjs/loader.js:653:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
    at Function.Module._load (internal/modules/cjs/loader.js:585:3)
    at Module.require (internal/modules/cjs/loader.js:692:17)
    at require (internal/modules/cjs/helpers.js:25:18)
    at Object.<anonymous> (/home/koen/Workspace/xyz/out/index.js:11:41)
    at Module._compile (internal/modules/cjs/loader.js:778:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)

It seems like there is an attempt to interpret the HTML as JavaScript code, leading to this unexpected behavior. Any insights or suggestions on why this might be happening? I'm currently at a roadblock...

Answer №1

Resolved the issue by incorporating Babel into the project setup. With the help of the index.d.ts, TypeScript was able to identify the data type (String) but struggled with parsing it.

If anyone else encounters a similar problem, follow these steps:

1. Setup babel core and cli

Execute the command:

npm install --save-dev @babel/cli @babel/core

2. Integrate Typescript preset

Babel will handle the conversion from Typescript to Javascript by installing the preset-typescript preset.

Run:

npm install --save-dev @babel/preset-typescript

Edit your babel.config.json in the project root directory (Create if not present) and include:

{
    "presets": [
        "@babel/preset-typescript"
    ]
}

3. Disabling tsc transpilation

To avoid conflicts, set compilerOptions.noEmit to true in the tsconfig.json.

4. Optional: Install @babel/preset-env preset

For ES2015+ functionality, install this syntax using the same approach as step 2.

5. Include babel-plugin-transform-html-import-to-string

Install the plugin that facilitates html file imports:

Command:

npm install --save-dev babel-plugin-transform-html-import-to-string

Open .babelrc in the project root (Create if nonexistent) and add:

{
    "plugins": [
        "transform-html-import-to-string"
    ]
}

6. Add script in package.json for building and running the application

"scripts": {
    "start": "tsc && babel src --out-dir lib --extensions '.ts,.tsx' && node lib/index.js"
}

tsc ensures correct typing while babel handles transpilation effectively.

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

Utilize external functions in evaluated code

After working with a TypeScript file containing the following code: import { functionTest } from './function_test' function runnerFunctionTest() { console.log("Test"); } export class Runner { run(source : string) { eva ...

Error: Angular ng-file-upload successfully uploads file, but Node.js fails to receive it

Currently, I am working on loading and cropping a file using Angular. Many thanks to https://github.com/danialfarid/ng-file-upload SignUp2ControllerTest -- $scope.upload --> data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAMgAAADICAYAAACtWK6eAAAg ...

At what point does angular2 @output get resolved?

Click on this link Here is the HTML code snippet: <chart [options]="options" (load)="saveGraphInstance($event.context)"></chart> <div (click)="switchGraph()">switch</div> <div (click)="showLoadingForce()">show loadin ...

I am looking to dynamically print countries from an array in my code based on the selected option

I'm in need of some simple code assistance. I want to display a list of countries that correspond to a selected letter, but I'm struggling to do so dynamically at the moment. For example, if I select the letter A from a dropdown menu, I want the ...

Generate a TypeScript generic function that maps class member types to class types

I am dealing with the following function in my codebase export async function batchEntitiesBy<Entity, T extends keyof Entity>( entityClass: EntityTarget<Entity> by: T, variables: readonly Entity[T][] ) { by: T, variables: readonly E ...

Uploading Files using the MERN Stack

Looking for guidance as a newcomer to MERN. I want to upload various file types, like Word Docx or text files, to my backend and run an OS command on the received file. There are several express middleware options available for this task, such as Multer a ...

What is the injection token used for a specialized constructor of a generic component?

I created a versatile material autocomplete feature that I plan to utilize for various API data such as countries, people, and positions. All of these datasets have common attributes: id, name. To address this, I defined an interface: export interface Auto ...

Passing extra data from the main application file (app.js) to routes in express

Can anyone advise me on how to pass extra data from app.js to express-resource routes? I am trying to figure it out but haven't had any luck yet. Specifically, I am using express-resource. // app.js var myAddOnData = 'abc'; app.resource(&ap ...

Encountering a TypeError while trying to execute a Node.js program

I’m encountering an issue on line 13 while trying to compile my Node.js application: var db = mc.db('course'); ^ TypeError: undefined is not a function at Object.<anonymous> (/app.js:13:13) at Module._compile (module. ...

Is it possible to utilize enums as keys in a Json structure?

I am currently utilizing TypeScript in conjunction with Node.js (MEAN stack). My aim is to incorporate an enum within the property/schema of a JSON object. An example of the enum would be: enum KeyEnums { A: "featureA", B: "featureB&qu ...

A guide on passing an ngFor object variable to a function

I am trying to display subcategories for each category in my *ngFor list. The subcategory data is retrieved from Firebase using the category_id, but I am struggling to pass the category_id from the HTML to the function for every member of the category. ho ...

Using axios to retrieve data and then sending it to a localhost server using express

I'm a beginner in javascript and currently experimenting with fetching data from an API and posting it to my own server (localhost). For fetching the data, I am using axios as shown below: async function getNCAA() { axios .get(`https://api.th ...

Customizing TinyMCE's font style menu options

Our platform utilizes TinyMCE as in-place editors to allow users to make live edits to content. However, a challenge arises when using a dark background with light text, as TinyMCE defaults to using this text color rather than black. https://i.sstatic.net ...

Tips for effectively utilizing a cart collection system

I am currently exploring how to utilize sessions for user tracking and updating my cart collection. Below is the code from my route.js file in an Express and Node application: app.post('/cart/:id', function (req, res) { if (!userKey) { ...

express-session: include additional information in 401 error reply

I have been exploring express-session and am curious about the ability to include extra information in the 401 response that express generates when a session is not discovered. My goal is to differentiate between an expired session and a missing session, ...

Altering the data in the database array is not within my capability

I'm having trouble updating the comment status, specifically the "approve" field. I've set up an AJAX script and it seems like the backend is working because I get a message after clicking the button. However, for some reason, the "approve" value ...

Struggling to dynamically update array values by comparing two arrays

I am faced with a scenario where I have two arrays within an Angular framework. One of the arrays is a regular array named A, containing values such as ['Stock_Number', 'Model', 'Type', 'Bill_Number'] The other arr ...

Ways to modify the access control to permit origin on a specific API URL in React

https://i.stack.imgur.com/tqQwO.png Is there a way to modify the access control allow origin for a URL API? I keep encountering error 500 whenever I try to load the page. After logging in, I included this code snippet: const options = { header ...

Adjust cursor location in a provided OnTypeFormattingEdits with Monaco Editor

I've implemented the following code to automatically close an XML tag when typing the '>' of an opening tag. Everything is working smoothly so far, however, I am trying to position the cursor between the tags instead of at the end of the ...

The directive [ngTemplateOutet] is functioning properly, however, the directive *ngTemplateOutlet is not functioning as expected

I have been struggling to create a component using ngTemplateOutlet to select an ng-template, but for some reason *ngTemplateOutlet is not working in this case (although [ngTemplateOutlet] is functioning correctly). Below is the code I am currently using: ...