19

I have installed the project with vue cli 3 but as the project grows, the import on the components are getting ugly, I end up importing a component like

import Component from '../../../../components/folder/Component.vue'

I just want to alias the src folder and do

import Component from '@components/folder/Component.vue'

I did read that I have to modify the vue.config.js, I have done it but the error is the same

Module not found: Error: Can't resolve '@components/Permissions/PermissionsTable'

This is my vue.config.js

  const path = require("path");

  const vueSrc = "./src";

  module.exports = {
    runtimeCompiler: true,
    css: {
      modules: true
    },
    configureWebpack: {
      resolve: {
        alias: {
          "@": path.join(__dirname, vueSrc)
        }
      }
    }
  };

Am I missing something? What else should I do?

Penny Liu
  • 15,447
  • 5
  • 79
  • 98
Carlos Salazar
  • 1,818
  • 5
  • 25
  • 48

3 Answers3

11

For Vue CLI you need to create a file in the root folder of project - jsconfig.json

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

and that's all, helped me with PhpStorm

Vlad
  • 599
  • 6
  • 12
  • This should actually be the correct answer...adding `extensions` to the vite configdoes not do anything. – Noopur Phalak Sep 21 '22 at 09:10
  • @NoopurPhalak, I didn't check how it works with Vite. With Vue 2.6 and @vue/cli 5.0.1 still working for for me. The question was asked more than 3 year ago, so probably you should find another solution. – Vlad Sep 21 '22 at 09:27
  • 1
    It works fine with vite as well. That is why I said, previously that this answer should be the accepted one. Actually even for @vue/cli this should have been the correct answer at that time... – Noopur Phalak Sep 22 '22 at 10:37
7

I was missing extensions: ['.js', '.vue', '.json'], and in the import I have to use '@/components/...'

Penny Liu
  • 15,447
  • 5
  • 79
  • 98
Carlos Salazar
  • 1,818
  • 5
  • 25
  • 48
7

The complete example:

const path = require("path");
const vueSrc = "./src";
module.exports = {
  runtimeCompiler: true,
  css: {
    modules: true
  },
  configureWebpack: {
    resolve: {
      alias: {
        "@": path.resolve(__dirname, vueSrc)
      },
      extensions: ['.js', '.vue', '.json']
    }
  }
};

Although I am not sure that extensions is the solution to the problem you had. This will just add the extensions in case you haven't written those in the import definition: https://webpack.js.org/configuration/resolve/#resolveextensions

I have a feeling it was rather a problem with the missing /. So instead of @components/Permissions/PermissionsTable it should have been @/components/Permissions/PermissionsTable because you did not add a / at the end of your vueSrc. So webpack will just attach it to ./src like this: ./srccomponents/Permissions/PermissionsTable.

Haiko
  • 143
  • 1
  • 6