Easy steps to bring in type definitions from an npm package using Vite

I am currently developing a package with several ts functions that will be utilized by multiple repositories, including mobile and web applications. In our team, we use vite as our primary build tool, which is also integrated into the repository.

Below is the contents of my vite.config.ts file:

import { defineConfig } from 'vite'
import dts from 'vite-plugin-dts'

export default defineConfig({
  build: {
    lib: { 
      name: 'project-name',
      entry: './src/index.ts',
      fileName: 'index',
      formats: ['cjs', 'umd'] 
    },
    outDir: 'dist'
  },
  plugins: [
    dts({
      insertTypesEntry: true 
    })
  ]
})

And here is the content of the tsconfig.json file:

{
  "compilerOptions": {
    "target": "esnext",
    "module": "esnext",
    "moduleResolution": "node",
    "esModuleInterop": true,
    "strict": true,
    "sourceMap": true,
    "declaration": true,
    "outDir": "dist",
    "declarationDir": "dist",
    "baseUrl": ".",
    "paths": {
      "@/": [
        "src/*"
      ]
    },
    "lib": [
      "esnext"
    ]
  },
  "include": [
    "src/**/*.ts",
    "src/**/*.tsx"
  ],
  "exclude": [
    "node_modules",
    "dist"
  ]
}

The issue I am facing is that when the package is installed in other repositories, the types are not being loaded properly. This results in all classes and functions having an any type, and even VS Code marking imported types as any. Type information is crucial for me, so I want to ensure it is exported correctly.

Methods I have attempted include:

  1. Trying the vite-tsconfig-paths plugin instead of vite-plugin-dts, but it failed to generate any *.d.ts files in the /dist directory
  2. Experimenting with various tsconfig options, as it seems the plugin might not be recognizing the tsconfig.json file (correctly named and located in the root directory)

Additional details:

  • Types are exported using the syntax export type ...
  • In src/index.ts, everything is imported, including types
  • The current index.d.ts file only contains one line:
export * from './index'

This means it exports the contents of index.js generated during the build process

Answer №1

There are instances where a package can be built without using vite or webpack. For example, in the situation described, solely relying on tsc was sufficient.

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

Trigger the Angular Dragula DropModel Event exclusively from left to right direction

In my application, I have set up two columns using dragula where I can easily drag and drop elements. <div class="taskboard-cards" [dragula]='"task-group"' [(dragulaModel)]="format"> <div class="tas ...

What could be causing the inability to update a newly logged-in user without refreshing the page?

Hello, I have encountered an issue with my application that involves registration and login functionality. The problem arises when a new user logs in, as I must refresh the page to get the current user information. I am currently using interpolation on the ...

There was a mistake: _v.context.$implicit.toggle cannot be used as a function

Exploring a basic recursive Treeview feature in angular4 with the code provided below. However, encountering an error when trying to expand the child view using toggle(). Encountering this exception error: ERROR TypeError: _v.context.$implicit.toggle i ...

Ways to address the issue of Node.js versions with odd numbers not qualifying for LTS status and being unsuitable for production node:16120 due to UnhandledPromiseRejectionWarning

After attempting to initiate a new Angular application with ng new app, I encountered the following error: Node.js version v11.0.0 detected. Odd numbered Node.js versions will not enter LTS status and should not be used for production. For more information ...

An uncaught error was thrown: throw er; // Event 'error' was not handled

` // server/index.js const express = require("express"); const PORT = process.env.PORT || 3001; const app = express(); app.get("/api", (req, res) => { res.json({ message: "Hello from Express!" }); }); app.lis ...

The 'React' namespace does not contain the exported members 'ConsumerProps' or 'ProviderProps'

Is it possible to install this library in Visual Studio with React version 15.0.35? Are there any other libraries that are compatible with this specific React version? import * as React from 'react'; import { RouteComponentProps, NavLink } from ...

Struggling to configure a React-Redux boilerplate

I encountered an issue with my previous boilerplate while working on a project, so I decided to switch to a different one. After exploring Github, I came across this repository that seemed simple and similar to what I needed. Upon cloning it and running np ...

What is the purpose of having a tsconfig.json file in every subdirectory, even if it just extends the main configuration file?

My goal is to streamline the configuration files in my front-end mono repo by utilizing Vite with React and TypeScript. At the root of my repository, I have set up a tsconfig.json file that contains all the necessary settings to run each project, including ...

Encountered an issue while trying to install npm for an existing Angular 4 project

As a newcomer to angular 4, I attempted to import an existing project into my local machine. Using npm install to fetch the nodes_modules as per the package.json of the project, resulted in the following error: Here is the error log: 36096 warn @angular/ ...

HTMLElement addition assignment failing due to whitespace issues

My current challenge involves adding letters to a HTMLElement one by one, but I'm noticing that whitespace disappears in the process. Here's an example: let s = "f o o b a r"; let e = document.createElement('span'); for (let i ...

Any suggestions on how to handle the 166 files that have been installed locally with gulp?

Once I completed the installation by running $ npm install gulp --save-dev npm WARN deprecated <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="e38e8a8d8a8e8297808ba3d1cdd3cdd2d3">[email protected]</a>: Make su ...

Error: A stream was expected, but instead you provided an object that is invalid. Acceptable options include an Observable, Promise, Array, or Iterable

I attempted to use map with a service call and encountered an error. After checking this post about 'subscribe is not defined in angular 2', I learned that for subscribing, we need to return from within the operators. Despite adding return statem ...

tips for concealing a row in the mui data grid

I am working on a data grid using MUI and I have a specific requirement to hide certain rows based on a condition in one of the columns. The issue is that while there are props available for hiding columns, such as hide there doesn't seem to be an eq ...

What strategies can be used to streamline NPM commands for a specific set of workspaces, such as filtering, including, excluding, using globs, grepping, or

Looking to set up a comprehensive NPM monorepo where I can execute commands on specific workspaces based on a category or pattern. Whether it's by subdirectory or a pattern in the workspace names like a prefix or suffix, it seems challenging to achie ...

How to efficiently import an external ES module from a URL using TypeScript

I've recently started experimenting with Observable notebooks and I must say, it's been a great experience so far. Now, my next goal is to integrate a notebook into my web app. The following vanilla JavaScript code using JavaScript modules accomp ...

Using Typescript types or a linter can help avoid mistakenly rendering the raw function in JSX instead of its executed return value

Seeking a resolution to prevent the recurring mistake I often make, as shown below: export function scratch_1 (props: scratch_1Props): ReactElement | null { function renderA (): string { return "A"; } function renderB (): string { ...

express-validator not providing any feedback from endpoint when integrated with TypeScript

I've been working on validating the response body for my endpoint, but I'm running into an issue where I'm not getting a response from that endpoint when using express-validator. I'm confident that I have followed the official documenta ...

The specified control name formControlName in the Angular reactive form cannot be located

Having encountered this issue multiple times on Stack Overflow without any success, I am reaching out for help to identify what I might be doing wrong. In my component : ngOnInit() { this.companyCreatForm = this._formBuilder.group({ name: [null, ...

Encountering error while trying to set up Hardhat using npm - "npm ERROR! Invalid URL code"

PS C:\Users\jawad\OneDrive\Desktop\NFT Project> npm install --save-dev hardhat npm ERR! code ERR_INVALID_URL npm ERR! Invalid URL npm ERR! A complete log of this run can be found in: C:\Users\jawad\AppData\L ...

Creating a Typescript mixin function that accepts a generic type from the main class

I am working with the code snippet shown below: // Types found on https://stackoverflow.com/a/55468194 type Constructor<T = {}> = new (...args: any[]) => T; /* turns A | B | C into A & B & C */ type UnionToIntersection<U> = (U extend ...