I'm struggling to find the perfect configuration for Vite, JSconfig, and Aliases in Visual Studio Code to optimize Intellisense and Autocomplete features

After exclusively using PHPStorm/Webstorm for years, I recently made the switch back to Visual Studio Code. The main reason behind this decision was the lightweight nature of VSCode and its widespread availability as a free tool, unlike paid services.

I started anew with Vite + Vue3 setup.

However, I encountered various issues related to imports, CTRL+Click navigation, and autocompletes.

In my Vite.config file, I included settings to enable aliases:

import { defineConfig } from "vite";
import { fileURLToPath, URL } from "url";
import vue from "@vitejs/plugin-vue";
import path from "path";

export default defineConfig({
    resolve: {
        extensions: [".js", ".json", ".vue", ".scss", ".css"],
        fallback: {
            crypto: path.resolve("crypto-browserify"),
            stream: path.resolve("stream-browserify"),
        },
        alias: {
            "@": fileURLToPath(new URL("./src", import.meta.url)),
            img: path.resolve(__dirname, "./public/img"),
        },
    },
    plugins: [vue()],
    test: {},
    server: {
        port: 8080,
    },
    build: {
        sourcemap: false,
        minify: false,
        assetsDir: "chunks",
    },
    css: {
        preprocessorOptions: {
            scss: {
                additionalData: `@use "sass:math"; @import "./src/assets/scss/v2/legacy.scss"; @import "./src/assets/scss/common.scss";`,
            },
        },
    },
});

With this configuration in place, I could import using the "@" alias, but lacked intellisense functionality. Imports and CTRL+click features were not working as expected.

Subsequently, by adding a jsconfig.json file:

{
    "compilerOptions": {
        "target": "ESNext",
        "baseUrl": ".",
        "paths": {
            "@/": ["src/*"]
        }
    }
}

I regained the ability to import components using "@" and benefitted from full intellisense and CTRL+click capabilities. However, I faced a setback as I lost intellisense support for node_modules.

So, while the vite/jsconfig setup provided intellisense for "@" alias, it compromised the import capabilities of node_modules.

Removing the vite.config alias configuration and jsconfig file restored intellisense for node_modules, albeit at the cost of project-specific intellisense.

I am seeking guidance on resolving this dilemma. Any assistance would be greatly appreciated.

To gain a better understanding, I have eliminated all npm import extensions from my setup.

Answer №1

The issue you're facing is related to the jsconfig.json file.

When a directory contains a jsconfig.json file, it signifies that the directory serves as the root of a JavaScript Project. This file outlines the root files and options for the features provided by the JavaScript language service (vscode).

Although not always necessary, there are instances where it can be beneficial, such as for customizing IntelliSense. Check out some examples for usage.

Additional Information:

jsconfig.json is derived from tsconfig.json, which is a configuration file for TypeScript. In comparison, jsconfig.json sets "allowJs" to true since no compilation is needed for JavaScript. These differences exist because jsconfig.json is based on tsconfig.json.

Furthermore, not all options mirror each other, including the target option:

The target parameter determines how JS features are handled. For instance, an arrow function () => this will be converted to a function expression if the target is ES5 or lower.
Adjusting target also alters the default value of lib.

Changes in target may impact vscode IntelliSense. Removing it can help restore expected functionality.

In essence, target influences IntelliSense in jsconfig.json.

To resolve your situation, simply add the following:


jsconfig.json

{
   "compilerOptions": {
      "baseUrl": ".",
      "paths": {
        "@/*": ["src/*"]
      }
   }
}

vite.config.js

alias: {
  '@/': path.resolve(__dirname, './src')
}

For more information on jsconfig.json for vscode, visit: here

Answer №2

I encountered a similar problem while using Visual Studio Code Intellisense and Autocomplete with Vite and import Aliases. Despite trying various configurations that didn't work, I managed to find a solution by making some adjustments. Here's the setup that worked for me:

tsconfig.json:

{
  "baseUrl": ".",
  "paths": {
    "@": ["./src"],
    "@components/*": ["./src/components/*"]
  },
}

vite.config.ts:

import path from 'path';

export default {
  resolve: {
    alias: {
      "@components": path.resolve(__dirname, "./src/components"),
    },
  },
};

Ensure to incorporate these configurations into your tsconfig.json and vite.config.ts files for Intellisense and Autocomplete to function properly. I hope this solution proves helpful!

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

Press the designated button located within a table's td element to retrieve the values of adjacent td elements

I need to implement a functionality where clicking a button within a <td> element will retrieve the values of other <td> elements within the same row (<tr>). Here is the current implementation: $(document).ready(function(){ ...

I am able to see the Redux props showing up in Redux DevTools, but for some reason they are not

I am facing an issue where I am passing a Redux prop to a component that is fetched from a payload. The payload successfully updates the state in my reducer and the component receives the prop (an array of objects fetched in the action) according to my Red ...

Using Knex.js to perform a case-insensitive search on an object with the whereIL

Still searching for a solution to this problem. I am attempting to pass an object with filters as keys and values. ex. const filters = { 'id': 12, 'first_name': john } function findBy(filter) { return db('quotes') ...

What is the best way to modify specific data retrieved from an API using Angular?

After successfully listing some data from an API using ngFor, I am facing an issue with editing the data. Whenever I click the edit button, it edits the entire data instead of just the specific row. Below is the code snippet for reference: HTML <table ...

Finding a way to reference multiple components within a mapping function

In order to set a ref to each project within the map function, I am trying to pass forwardRef from child to parent. At the moment, I am only able to get a single Project. However, I need to set refs to an array list so I can work with it. Below is what I h ...

The React MUI Tab component triggers a re-render and clears the states of its child components

In our endeavor to create a Tab Page using React MUI, we aim for each Tab to contain a child component. While there are no issues when adding these child components individually to a page without tabs, problems arise when incorporating them within the Tab ...

Using a JSP page to trigger a JavaScript function

I am attempting to execute an in-page JavaScript function from within a JSP page. Here is the code snippet, however, the JavaScript functions do not appear to be executing when the JSP page loads on the client side. Is there anything incorrect with the a ...

Creating a CSS animation to mimic the fading in and out effect of the Mac scrollbar when scrolling begins

My journey begins with this: *::-webkit-scrollbar { } *::-webkit-scrollbar-button { } *::-webkit-scrollbar-track { } *::-webkit-scrollbar-track-piece { } *::-webkit-scrollbar-thumb:active { width: 6px; background-color: red; } *::-webkit-scr ...

Angular UI Bootstrap Typeahead - Apply a class when the element is added to the document body

In my current project, I am utilizing angular bootstrap typeahead with multiple instances. Some of these instances are directly appended to the body using the "typeahead-append-to-body" option. Now, I have a specific instance where I need to customize the ...

Is it possible to set a read-only attribute using getElementByName method

To make a text field "readonly" by placing JavaScript code inside an external JS file, the HTML page cannot be directly modified because it is located on a remote server. However, interaction can be done by adding code in an external JS file hosted on a pe ...

What is the best way to transfer the JWT token from the server to the client using an HTTP header?

I have been searching for an answer on how to pass the JWT Token from the client to the server securely, but I am not satisfied with the explanations I found. Everyone talks about the most secure way to transfer the JWT token using HTTP headers instead of ...

"Having trouble implementing sorting functionality on a click event in a React application with Material-UI table

Default behavior displays data in ascending order. Clicking on the table header should toggle between descending and ascending orders. Load Data in ascending order -> On click, change to descending order -> Again on click, change to ascending -> ...

unable to access various attributes in an angular directive

I have a particular HTML setup that effectively outlines each attribute's value through a distinct "attachment" directive. These values are located in the attrs list of said directive, which is within a modal file upload form. <p>For Testing Pu ...

Error: The term "Particles" has not been defined

I'm attempting to integrate code from a website into my project, but encountered an error when the particles failed to run after adding it. I downloaded and installed particle.js from "https://github.com/marcbruederlin/particles.js/issues" for this pu ...

PHP and MySQL form is not being updated with new data

In my database, the fields include: id,name,email_id,address,phone_no,username,password,category,date <?php include_once('connect_to_mysql.php'); if(isset($_POST["submit"])){ $a=mysql_real_escape_string($_POST["name"]); ...

Utilizing property validation in your codebase

How can I set up my code to display a warning in the console if the value of the Prop is not a string? The player-name prop should always be a string. If this: <greet :player-name="5"></greet> contains a number, I want my code below to generat ...

Element UI defaults to using the default theme

Recently, I've been working on a Vue project set up with webpack. I'm interested in incorporating element UI into my UI library. So, I went ahead and ran the command below in my terminal: npm i element-ui -S After that, I added the following ...

Using React to integrate Zurb Foundation's slider by binding moved.zf.slider

Update: I have included the complete code as requested. There are a few modifications from the original version. I am attempting to integrate the foundation slider with react and ES6. The slider is supposed to trigger an event named moved.zf.slider when i ...

console displaying indentation problems with laravel and vue

I am currently utilizing Vue within Laravel and encountering a multitude of indentation errors in the console. Here is an excerpt from my package.json file: "private": true, "scripts": { "clean": "rimraf public/build", "build": "npm run clean & ...