Make VS code read webpack.config and recognize path with alias?

Solution 1:

update [email protected] and you can map the same webpack aliases on tsconfig.json by adding:

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

Solution 2:

I ran into a similar issue. Because I was using javascript rather than typescript, I had to create a jsconfig.json file and use the paths option appropriately.

Assuming a directory structure like this:

.
├── src
│   ├── foo.js
│   ├── jsconfig.json # your vscode js config
│   └── my-module     # folder you're aliasing
│       └── bar.js
└── webpack.config.js # your webpack config

This wound up working for me:

  1. Set up webpack resolve alias:

    var path = require('path');
    module.exports = {
      resolve: {
        alias: {
          "my-module": path.resolve(__dirname, './src/my-module')
        }
      },
      // ... other webpack options
    };
    
  2. Modify jsconfig.json in your src folder:

    {
      "compilerOptions": {
        "target": "es6",
        "paths": {
          "my-module": ["./my-module"]
        }
      }
    }
    
  3. Use the alias:

    // in foo.js
    import Bar from 'my-module/bar';
    Bar.quack();
    

Solution 3:

Install VSCode extension PathIntellisense .

To open your VSCode setting file, you can press command+, on macOS(on Windows is ctrl+,), find "a pair of curly brackets button" on the top right corner, click it.

In my situation, I want to use the symbol @ as an alias of the path ./src . So I add this configuration to my VSCode setting file:

  "path-intellisense.mappings": {
    "@": "${workspaceRoot}/src"
  }

Use ${workspaceRoot} when the path should be relative to the current root of the current project.

You can find the official example here .


Original answer:

I use the VSCode extension PathIntellisense .

Configure this setting in my VSCode setting file.

Now VSCode could recognize the path with the alias.

Solution 4:

You need to specify the paths and baseUrl fields in your jsconfig.json file.

{
    "compilerOptions": {
        "jsx": "react",
        "target": "ES6",
        "allowSyntheticDefaultImports": true,
        "baseUrl": "./",
        "paths": {
            "~/*": ["./app/*"]
        }
    },
    "exclude": [
        "node_modules"
    ]
}

See path mapping documentation

Solution 5:

Use Path Autocomplete extension for VSCode

It's better than PathIntellisense for me.

Just add Config:

  {
    "javascript.suggest.paths": false, // disable default suggestion
    "path-autocomplete.extensionOnImport": true,
    "path-autocomplete.pathMappings": {
    "@": "${folder}/src" //custom what you want
  },

Work screenshot