Utilizing NPM Workspace Project in conjunction with Vite to eliminate the necessity of the dist folder during the Vite build process

I am currently working on a project that involves a module using full path exports instead of index files.

This project is divided into 2 NPM workspaces: one called core and the other called examples.

The challenge I am facing is avoiding long import paths like

@my-project/core/dist/plugins/Input

Although I have managed to configure Typscript to compile without requiring dist in the path, Vite is unable to build it and throws an error stating it cannot find the necessary code:

Error: [vite]: Rollup failed to resolve import "@my-project/core/plugins/Input"

Typescript seems to be fine after some tweaking in the package.json file:

"typesVersions": {
    "*": {
      "*": [
        "./dist/*"
      ]
    }
  },

I suspect there might be something in my Vite configuration causing this issue. Here is how my config looks:

import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';

export default defineConfig(() => {
  return {
    build: {
      outDir: 'build',
    },
    plugins: [
      react({
        // Use React plugin in all *.jsx and *.tsx files
        include: '**/*.{jsx,tsx}',
      }),
    ],
    server: {
      port: 3000,
      host: true,
    },
    preview: {
      port: 4000,
    },
  };
});

I have tried various approaches to fix this issue and although I have made progress with TypeScript, I am still struggling to make Vite work properly. Any help or guidance would be greatly appreciated!

Answer №1

To simplify the importing process of a package, consider setting export paths in the package.json file. Here's an example:

{
  "name": "@my-project/core",
  ...
  "exports": {
    ".": "./dist/index.js",
    "./plugins/Input": "./dist/plugins/Input",
  }
}

After configuring this, you can import the subfolder like so:

import { stuff } from '@my-project/core/plugins/Input'

If the package is meant for public use, it would be beneficial to include ESM and CJS export paths to accommodate both sets of outputs:

        ".": {
            "import": "./dist/index.js",
            "require": "./dist/cjs/index.cjs"
        },

Feel free to reach out with any questions or updates on your progress!

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

Leveraging File functionality in TypeScript

In the process of developing a web application with Angular 4 and Typescript, I encountered an issue while attempting to retrieve the date of a file for upload. Specifically, when trying to access the lastModified property of a File object, Typescript retu ...

The initial values of Typescript class members are merged directly into the class constructor

This issue has been well documented (check out Initializing variables inline during declaration vs in the constructor in Angular with TS on SO for reference), but it can lead to challenging memory problems. Take a look at the example below class Bar { ...

I am attempting to code a program but it keeps displaying errors

What is hierarchical inheritance in AngularJS? I have been attempting to implement it, but I keep encountering errors. import {SecondcomponentComponent} from './secondcomponent/secondcomponent.Component'; import {thirdcomponentcomponent} from & ...

When I try to execute `npm start` on Ubuntu 16.04, I encounter npm errors

My Ubuntu 16.04 OS has node v7.10.1 and npm v4.2.0 installed. I encountered an error when trying to start npm or sudo start npm. Everything was working fine this morning, but now I'm getting errors. Can someone please help me troubleshoot this? npm E ...

Switch the following line utilizing a regular expression

Currently, I am facing a challenge with a large file that needs translation for the WordPress LocoTranslate plugin. Specifically, I need to translate the content within the msgstr quotes based on the content in the msgid quotes. An example of this is: #: . ...

The Material UI Datagrid is failing to display any data

I'm currently facing a challenge that has left me scratching my head. I've implemented Material UI Datagrids, but for some reason, I can't get it to populate with data, and the reason eludes me. Even though the Component profiler shows that ...

Some files are missing when performing an npm install for a local package

My project is structured like this: ├── functions/ │ ├── src │ ├── lib │ ├── package.json ├── shared/ │ ├── src │ | ├── index.ts | | ├── interfaces.ts | | └── validator_cl ...

Executing npm start command from ExecStart in a systemctl service file

Check out the service file below: [Unit] Description=MyApp After=syslog.target network.target StartLimitIntervalSec=0 [Service] Type=simple Restart=always RestartSec=1 WorkingDirectory=/opt/nodejs-sites/MyApp ExecStart=/usr/bin/npm start Environment=NODE_ ...

Inheritance-based generic type inference in Typescript

Take a look at this piece of code: class A<T> { t?: T; } interface B {} class C implements A<B> {} function f<T1 extends A<T2>, T2>(a: T1): T2 | undefined { return a.t; } const result = f(new C()); const result2 = f(new A<B> ...

Struggling to integrate Docker compatibility into an established NextJS project, encountering the frustrating "stat app/.next/standalone: file does not exist" message

I'm currently in the process of enhancing my existing NextJS + TypeScript project with Docker support and preparing to deploy it on Google Cloud Run. To achieve this, I've been referring to a helpful guide available at: https://github.com/vercel/ ...

Exploring the concept of object inheritance in Angular 5 with Typescript

I'm facing a challenge related to inheritance while building my initial angular 5 application. The error message I encounter is: Property 'message' does not exist on type 'CouponEvent', as reported by the angular-cli. export class ...

The module that npm is looking for cannot be found

I've searched extensively through Google and StackOverflow, reading countless threads about similar issues, but unfortunately, nothing has resolved my problem. The issue at hand is with npm installation on my machine - something seems to be going wron ...

Ensuring proper extension of Request headers in Typescript

I am having trouble retrieving the userId from req.headers, how can I fix this issue? Initially, I attempted the following: interface ISpot{ thumbnail: File, company: string, price: number, techs: string } interface IReqCustom<T& ...

What is the best way to position Scroll near a mat row in Angular?

With over 20 records loaded into an Angular Material table, I am experiencing an issue where clicking on the last row causes the scroll position to jump to the top of the page. I would like the scroll position to be set near the clicked row instead. Is th ...

Mongoose fails to add an object to an array

I am facing an issue with my express application where comments are not being inserted into posts. Even though there are no errors displayed, the comments are not being added when posting via Postman. I have tried various solutions like this and this, but ...

Converting seconds to days, hours, and seconds using Moment.js in a ReactJS and TypeScript environment

I would like to achieve the following: I have a value in seconds. When I pass this value to the moment function, I expect to receive the corresponding values for days, hours, and seconds. I have utilized moment.js and managed to output logs as well, but I ...

Passing an array of objects as properties in React components

My functional component looks like this: function ItemList({ items }: ItemProps[]) { return <p>items[0].name</p> } Here is how I'm creating it: <ItemList items={items} /> The array items contains objects in the format [{name: &ap ...

Switch from using getElementById to useRef in React components

There is a requirement to update a functional component that currently uses getElementById to instead utilize the useRef hook. The original code snippet is as follows: import React, { useState, useEffect, useRef } from 'react'; import { createPo ...

`The Importance of Validating Enum Arrays in Typescript Using Class-Validator`

Is there a way to validate an array of enums in a DTO without getting misleading error messages? Here is an example of my DTO: import { IsArray, IsEmail, IsEnum, IsIn, IsNotEmpty, IsString } from "class-validator"; import { UserAction, UserModul ...

npm retrieve objectGUID from Active Directory

I've been trying to retrieve unique IDs for entities in my Nodejs application, but I'm having trouble. I'm using the following module: https://www.npmjs.com/package/activedirectory When pulling for groups, I can't seem to fetch the ...