Tips for bringing in specialized document formats in Typescript

For a fun side project, I am in the process of creating a "framework" to easily develop native web components. One aspect of this involves using a webpack loader to parse XML within custom .comp files and export an es2015 class. However, I've encountered an issue when trying to import these .comp files into my typescript files.

Importing these custom files in a regular javascript file works perfectly fine; the loader runs smoothly and produces the expected output. But, attempting to import them in a typescript file results in the error message,

Cannot find module 'test/test.comp'
. I even tried creating an empty declaration file, which changed the error to
File '[path]/test/test.d.ts' is not a module

Here's what my webpack config looks like:

mode: 'development',
watch: true,
entry: './test/main.js',
output: {
    filename: 'bundle.js',
    path: path.resolve(__dirname, 'build')
},
module: {
    rules: [
        {
            test: /\.ts/,
            use: 'ts-loader',
            exclude: /node_modules/
        },
        {
            test: /\.comp/,
            use: path.resolve(__dirname, 'core/compose-loader.js'),
            exclude: /node_modules/
        }
    ]
},
resolve: {
    extensions: ['.js', '.ts', '.comp'],
    alias: {
        'core': path.resolve(__dirname, "core/"),
        'test': path.resolve(__dirname, "test/")
    }
}

Here's a snippet from my tsconfig.json file:

{
    "compilerOptions": {
        "outDir": "build",
        "baseUrl": ".",
        "paths": {
            "core": ["core/*"],
            "test": ["test/*"]
        },
        "target": "es2015",
        "typeRoots": ["./core"]

    },
    "include": [
        "test/*.ts"
    ],
    "exclude": [
        "core",
        "node_modules",
        "**/*.comp"
    ]
}

Answer №1

To set the types for these files, you can create a *.comp file in a declarations.d.ts file (you can name it whatever you want).

declare module "*.comp" {
  const value: any; // Feel free to improve type definitions here.
  export default value;
}

You might also need to include this in your tsconfig.json's typeRoots section.

{
    "compilerOptions": {
        // Other configurations...
        "typeRoots": [
            "./src/declarations.d.ts"
        ]
    }
}

After that, using

import value from "./test.comp"
should function correctly (at least with the types).

Note: when using VSCode, make sure the definition file is not located above the import in the folder structure.

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

Why won't the Laravel Livewire click function work after the PJAX container refresh?

I am currently using the pjax library in my application, and I recently integrated Livewire. However, I am facing difficulties in making them work together. Specifically, my issue is as follows: In my application, I have a grid displaying products with an ...

Real-time data updates not working in jQuery data table

I am currently dealing with a data table and using ajax to fetch data for display on my HTML DOM page. However, I have encountered an issue after implementing server-side processing for the data table. Even though I can successfully retrieve records in my ...

Directive containing tracking code script

I'm working on creating a directive to dynamically include tracking code scripts in my main page: <trackingcode trackingcodevalue="{{padCtrl.trackingnumber}}"></trackingcode> This is the directive I have set up: (function () { 'use ...

Send an AJAX request to the server without waiting for a response using a JavaScript variable

My click counter is not sending variables to the server. I have tried finding examples on how to do this, but no matter what I attempt, the data is not being sent to the server. It seems like using AJAX would be the best option, but I must be doing someth ...

Accessing information from a database table using Highchart and Ruby on Rails (ROR

I have a Ruby on Rails application that utilizes highcharts. I am currently working on enhancing it to display the amount of time spent on specific projects. To demonstrate what I am trying to achieve, I have created a JSFiddle example which can be found h ...

Utilize JQuery to inject both standard HTML elements and safely rendered escaped HTML onto a webpage

After storing some data in firebase that can be retrieved on the client side, I use JQuery to add it to the HTML. Although the process of prepending the data to the DOM element is straightforward, there is a security concern as raw code can make the applic ...

Having trouble importing or resolving files with ts-loader or css-loader?

Struggling to incorporate css modules by utilizing style-loader and css-loader in my project. I am facing difficulties understanding the root cause, unsure if it's ts-loader or css-loader to blame. webpack.config.js const path = require('path&a ...

JS/Apps Script: Passing object and its keys as function parameters

When working with Google Apps Script, I have a specific task that involves looping through data and writing only certain keys to a sheet. I want this looping operation to be done in a separate function rather than directly in the main function, as it will ...

How to prevent the collapse action when clicking a button inside a div in Bootstrap 5 using data-bs-toggle

My div contains a data-bs-toggle attribute along with buttons. https://i.sstatic.net/RzagX.png When clicking on the panel, it collapses. However, I do not want this collapse event to trigger when clicking the buttons. Is there a way to control this behav ...

Triggering a JQuery Toggle Button

This is the code I'm currently working with: $('.access a').toggle(function() { $('link').attr('href', 'styles/accessstyles.css'); $('body').css('font-size', '16px'); }, fu ...

View setup in progress

I'm interested in implementing something along these lines: app.config(function($routeProvider){ $routeProvider.when('products/list', { controller: 'ProductListCtrl', templateUrl : 'products/list/view.html', ...

React Native: The function `useContext.getItemsCount()` is returning a value of undefined, which is not an object

As a newcomer to React Native, I encountered an error when calling getItemsCount. *To view images, please click on the following links: https://i.sstatic.net/wbwjZ.png This snippet shows the code for CartIcon.js: import React, {useContext} from 'r ...

Adjusting the image placement within a modal window (using bootstrap 3)

Behold, an example modal: <!-- Large Modal --> <div class="modal fade bs-example-modal-lg" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel"> <div class="modal-dialog modal-lg"> <div class="modal-content"> ...

Dealing with special characters in a json XMLHttpRequest: A guide

I'm currently grappling with the best approach for handling special or foreign characters within an AJAX request. My current test code is as follows: var xmlhttp = new XMLHttpRequest(); xmlhttp.open("POST","test.json",true); xmlhttp.setRequestHeader ...

Verify a unique cross-field rule for comparing two time strings, customized by Vee

I am currently facing an issue with validating two time strings in my buefy form using vue. The goal is to ensure that the second time input does not exceed a one-hour difference from the first time input. Both time fields have granularity down to millisec ...

Determining the Maximum Number of Characters Allowed in a Div Using jQuery

Could anyone provide guidance on how to populate a div with single characters? I want the div to span the width of the viewport. The code to get the width is: $(window).width(); I would like JavaScript to generate HTML similar to this: <div id="text ...

What could be causing the poor performance of WebGPU in my benchmark when compared to WebGL?

After running my benchmark code on the Latest Chrome Canary on Win11 and disabling vsync with unlocked fps, I noticed that WebGPU has around 1/3 the FPS of WebGL. I'm struggling to understand the reason behind this performance difference. Here is the ...

Encountering a navCtrl problem in Ionic 3 while attempting to utilize it within a service

I am currently working on a feature to automatically route users to the Login Page when their token expires. However, I am encountering an issue with red lines appearing under certain parts of my code. return next.handle(_req).do((event: HttpEvent< ...

We are in need of a provider for the Ionic Network native plugin

I have encountered an issue while trying to use Ionics native plugin "Network" as it fails due to a missing provider. To prevent any errors, I performed a fresh installation of Ionic along with the necessary dependencies: ionic cordova plugin add cordova- ...

Mongoose failing to retrieve data from MongoDB

In my code, I am utilizing data from the database: Assignment and the Collection: todolist. The code is designed to interact with MongoDB in order to add, delete, or list the JSON in the collection. To properly explain the issue, I will first showcase the ...