Declaring named exports dynamically in TypeScript using a d.ts file

I have developed a collection of VueJs components in TypeScript and I want to be able to use them globally in my Vue instance using Vue.use(library), or individually through named imports in Vue components.

While everything functions correctly, I am facing some challenges with TypeScript when it comes to declaring all the components in the index.d.ts file dynamically (due to the large number of components and the desire to avoid manual declaration).

This approach works:

import { Component1, Component2 } from 'my-library';

declare module 'my-library' {
  declare const lib: PluginFunction<any>;
  export default lib;

  export { Component1, Component2 } from 'my-library';
}

However, I am seeking a method to achieve this for all components without importing and exporting them individually.

I attempted something similar to:


...
export * from 'my-library'
...

or

import * as components from 'my-library';

declare module 'my-library' {
  declare const lib: PluginFunction<any>;
  export default lib;

  Object.entries(components).forEach(([componentName, component]) => {
    export { component as componentName };
    // or
    // export { component };
  })
}

Unfortunately, these methods did not work, as I encountered TS errors when attempting to import a specific component like Component1:

"Cannot resolve symbol 'Component1' TS2614: Module '"my-library"' has no exported member 'Component1'. Did you mean to use 'import Component1 from "my-library"' instead?"

ps: everything works fine if I use a //@ts-ignore before the import.

Any thoughts or suggestions?

Answer №1

It seems that TypeScript imposes stricter requirements at build time for its type checking functionality, compared to JavaScript. This limitation leads to reduced flexibility as TypeScript prioritizes having definitions at compile time instead of runtime.

Therefore, it is not possible to achieve this. The only workaround is to export everything within a keyed object. However, this approach requires importing the entire object in another file, rather than accessing specific parts of it.

Here is an example scenario using a File.vue component:

<CustomNamedThing/>

<script>
import Foo from './yourfile.ts'
components: {
  CustomNamedThing: Foo.CustomNamedThing
}, ...


</script>

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

The syntax comparison between CommonJS and AMD modules in a modular AngularJS application

Apologies if this question has already been addressed, but I couldn't find any relevant information. Currently, I'm in the process of refactoring a large AngularJS application by creating components as AMD modules. The build process (grunt) utili ...

Tips for instructing Vue-Cli 3 to disregard modifications in the public directory

I am facing an issue with my CPU reaching 100% because I have to store a large number of js files in the public/js folder. The file path looks like this: src public - js - 1.js - 2.js - ... node_modules These js files do not ...

display dynamic graphs using json data from a php backend

I'm having trouble displaying a graph using JSON data in Highcharts. Here is a sample of what I need: http://jsfiddle.net/gh/get/jquery/1.9.1/highslide-software/highcharts.com/tree/master/samples/highcharts/demo/column-rotated-labels/ The file values ...

Is there a way to transfer a JSON array from a text/javascript block to a runat=server block within the context of ExactTarget/Salesforce Marketing Cloud?

I have a page containing two <script> elements: one is running locally and the other one is running on the ExactTarget server: <script type="text/javascript"> var results = localStorage.getItem('results'); var results = JSON.parse(re ...

What is the best way to link this to a function in AngularIO's Observable::subscribe method?

Many examples use the Observable.subscribe() function in AngularIO. However, I have only seen anonymous functions being used like this: bar().subscribe(data => this.data = data, ...); When I try to use a function from the same class like this: update ...

Is there a way to deactivate a tab when it's active and reactivate it upon clicking another tab in Angular?

<a class="nav-link" routerLink="/books" routerLinkActive="active (click)="bookTabIsClicked()" > Books </a> I am currently teaching myself Angular. I need help with disabling this tab when it is active ...

Linking Vue.js drop-down menus to Ruby on Rails

I've encountered a challenge while building a Vue.js form with select boxes. Despite successfully posting the data to my Rails app, I face an issue when editing the object later on. The pre-selected values in the select boxes do not match what was ori ...

An issue has occurred: The module named 'ApprovalModule' must be compiled using the JIT compiler, however, the necessary compiler '@angular/compiler' is not currently accessible

Issue: Error: The NgModule 'ApprovalModule' needs to be compiled using the JIT compiler, but '@angular/compiler' is not available. JIT compilation is not recommended for production environments. Consider using AOT mode instead. Alterna ...

Activate single elements one at a time

If you want to understand the question better, take a look at my code on jsfiddle. Each Div contains only one link. When you click on the link, it sets the Div to active and shows a hidden Div within it. Clicking the link again toggles the active style an ...

Strategies for handling failed promises within a Promise.all operation instantly

Currently, I am developing a file upload web application where I aim to enable the simultaneous upload of multiple files (let's say 5). In case one of the files fails to upload, my goal is to display a RETRY button next to that specific file for immed ...

Is it possible that ngChange does not trigger when the model is updated through code?

According to the documentation, the ngChange directive will not trigger if the model is updated programmatically rather than through a change in the input value. Does this imply that once you programmatically modify the model, you are unable to utilize ng ...

Assist me with Twitter

Seeking assistance with a coding issue related to displaying Twitter posts on a website. I have found a code snippet that accomplishes this: //Scrolling of tweets in the footer $(function () { var tweetVP = $("#footerTweetsViewport"); arrTweetNav ...

Tips for implementing Peer.js in Next.js using TypeScript?

Next.js has the ability to run on the server side, which can result in Peer.js throwing errors when used with Next.js. One user on Stack Overflow explains this issue: The error is likely due to peer js performing side effects during import. The suggest ...

React's useState function causes the entire application to crash

Currently, I am working on setting up a basic menu using ASP.net core 2.1, Typescript 3.2.1, material-ui 3.8.3, and React 16.7.0. However, upon running the application, it crashes at the line containing useState showing the error message as TypeError: reac ...

Troubleshooting: Why is VueJS computed filter function failing to work

Currently, I am working on incorporating the functionality outlined in this Vuejs Search filter article. However, the function inside the computed property is not working as expected, and it's not even logging anything. Below is a snippet of my code: ...

The ability to rate the product in Livewire:Laravel is exclusively reserved for buyers

I have integrated the Livewire rating system into my Laravel e-commerce platform. Currently, all users can rate and comment on any product. However, I want to restrict this privilege to only buyers. ProductRatings.php class ProductRatings extends Componen ...

retrieve the value of a textarea element from an HTML table

Is there a way to extract data from a nested table's textarea using the row index? I attempted the following code snippet but it did not work. var note = document.getElementById($index).cells[3]; var y = document.getElementsByTagName("textarea").valu ...

eliminate any redundant use of generics

Recently, I attempted to create a pull request on GitHub by adding generics to a method call. This method passes the generically typed data to an interface that determines the return type of its methods. However, the linter started flagging an issue: ERR ...

Master the art of utilizing watchers and computed properties for intricate computations

Here's the scenario I'm dealing with: The user is able to enter Working hours and expenses, From these inputs, a calculation needs to be performed to determine the final value, with both vat and payrate being pre-defined constants. pay_amount ...

NuxtJS store is not fetching values from local storage correctly and returning them as undefined

In my Nuxt application, I encountered an issue where one of the components in the mounted lifecycle hook is unable to retrieve a value from the state store. This value is stored locally, but for some reason, the store returns it as undefined. Interestingly ...