Utilizing absolute path imports in Vite originating from the src directory

What are the necessary changes to configuration files in a react + ts + vite project to allow for imports like this:

import x from 'src/components/x' 

Currently, with the default setup, we encounter the following error:

Failed to resolve import "src/components/x" from "src/components/y.ts". Does the file exist?

Answer №1

Discovered a solution that actually works here

import { defineConfig } from 'vite'
import path from 'path'
import { readdirSync } from 'fs'

const absolutePathAliases: { [key: string]: string } = {};
// Root resources folder
const srcPath = path.resolve('./resources/');
// Adjust the regex here to include .vue, .js, .jsx, etc.. files from the resources/ folder
const srcRootContent = readdirSync(srcPath, { withFileTypes: true }).map((dirent) => dirent.name.replace(/(\.ts){1}(x?)/, ''));

srcRootContent.forEach((directory) => {
  absolutePathAliases[directory] = path.join(srcPath, directory);
});

export default defineConfig({
  root: 'resources',
  resolve: {
    alias: {
      ...absolutePathAliases
    }
  },

  build: {
    rollupOptions: {
      input: '/main.ts'
    }
  }
});

Unsure if there's a more efficient or straightforward method available. It seems like something akin to baseUrl in a typescript configuration should suffice, but haven't come across an equivalent.

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

What is the best way to reference class variables and methods within a callback function in Typescript?

While working on my Angular project with the Highcharts API, I encountered a situation where I needed to pass a state code to a class level method after drilling down to a specific map location. Below is the snippet of my current code: ngOnInit() { this. ...

Is there any special significance to the statement x = x in TypeScript/Angular?

The Fontawesome/Angular documentation provides an example of adding an explicit reference, which may not be as convenient as using the library directly. If you value "explicit is better than implicit," then this method might be for you. The example code sn ...

What is the best way to structure this React state container for modularity?

At my workplace, we have developed a state container hook for our React application and related packages. Before discussing what I'd like to achieve with this hook, let me provide some background information. Here is the functional code that's co ...

The Angular Compiler was identified, however it turned out to be an incorrect class instance

Although this question has been asked before, I have exhausted all possible solutions that were suggested. Unfortunately, I still cannot resolve it on my own. Any assistance would be greatly appreciated. Error: ERROR in ./src/main.ts Module build failed: ...

Creating dynamic keys using Typescript and JSON data format

Currently, I am developing an application using Typescript and React Native. Within my app, I have a JSON file containing information about poker hands that needs to be accessed. The structure of the JSON data is as follows: { "22": [ [ ...

What is the process for incorporating attribute values when constructing XML with fast-xml-parser?

Latest fast-xml-parser update: version 4.3.6 Description I'm trying to incorporate an xml attribute (tokenized="true") in this format : <custom-tag tokenized="true">test test &gt; 14</custom-tag> Input Code var def ...

Choose from the Angular enum options

I am working with an enum called LogLevel that looks like this: export enum LogLevel { DEBUG = 'DEBUG', INFO = 'INFO', WARNING = 'WARNING', ERROR = 'ERROR' } My goal is to create a dropdown select el ...

The button event listener in React fails to trigger without a page refresh

Within my index.html file, I have included the following code snippet: <head> ... <script type="text/javascript" src="https://mysrc.com/something.js&collectorId=f8n0soi9" </script> <script ...

Exploring Angular 5: Managing HTTP Headers and Utilizing URL Parameters

I am currently working on an Angular project that involves third-party authentication, which redirects to our app with additional information in the HTTP headers. Here are the questions I have: What is the best way to extract the information from the HT ...

Error in hook order occurs when rendering various components

A discrepancy was encountered in React when attempting to render different components Warning: React has detected a change in the order of Hooks called by GenericDialog. This can result in bugs and errors if left unresolved. Previous render Next ren ...

Youngster listens for guardian's occurrence in Angular 2

While the Angular documentation covers how to listen for child events from parents, my situation is actually the opposite. In my application, I have an 'admin.component' that serves as the layout view for the admin page, including elements such a ...

How can I prevent the creation of undefined fields in Typescript when initializing a new object?

I'm working with the data structure Player: type Player = { id: Scalars['ID']; name: Scalars["String"]; age: Scalars["Int"]; description?: Maybe<Scalars["String"]>; __typename?: "Player" ...

Challenges of Vue 3 Typescript ComputedRef

I've run into some challenges with Typescript and Vue3. It seems like I might be using Typescript incorrectly in this case. I set up a store using Vue's Composition API. import {computed, reactive} from "vue"; const state = reactive({ ...

error: encountering issue with Vue TypeScript Jest tests - '$store' property is undefined

I've been facing issues with my tests failing after a recent npm install. I've tried adjusting versions up and down, but haven't had any success. Interestingly, the $store isn't directly used in any of the components or tests. Despit ...

When working with Typescript, an error is thrown if property "p" does not exist on one of the classes that are OR

In my component class, I have a property called renderContent which can be of either LessonPageType or TaskPageType based on the input value. Below is the code snippet from my component: import {ChangeDetectionStrategy, Component, HostListener, Input, OnI ...

When the appdir is utilized, the subsequent export process encounters a failure with the error message "PageNotFoundError: Module for page /(...) not

I have implemented NextJS with the experimental appDir flag and organized my pages in the following manner: https://i.stack.imgur.com/M7r0k.png My layout.tsx file at the root and onboard look like this: export default function DefaultLayout({ children }) ...

Implementing reCaptcha on React Native: A Step-by-Step Guide

Currently, I am in the process of integrating a reCaptcha validator into a login screen for a react-native application that needs to function seamlessly on both web and mobile platforms. Despite being relatively new to programming and lacking experience w ...

Step-by-step guide on incorporating an external JavaScript library into an Ionic 3 TypeScript project

As part of a project, I am tasked with creating a custom thermostat app. While I initially wanted to use Ionic for this task, I encountered some difficulty in integrating the provided API into my project. The API.js file contains all the necessary function ...

What is the contrast between element.getAttribute() value and a String in protractor?

When using protractor and typescript, I need to verify that the text saved in a textbox matches a certain string by comparing it with the resulting value of element.getAttribute("value"). Unfortunately, getText() does not work for this scenario b ...

Conditionally displaying a select element using Ng-if

Is there a way to display content based on the user's selection in an HTML form? Here is how I attempted to do it: <select class="form-control" id="Intervencion" > <option selected disabled></option> <option (click)="show ...