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

前端 未结 4 809
轻奢々
轻奢々 2020-12-14 00:08

I\'m working with Webpack and Visual Studio Code and in order to avoid things like:

import { AuthenticationService } from \'../../../services/authentication/         


        
相关标签:
4条回答
  • 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();
      
    0 讨论(0)
  • 2020-12-14 00:44

    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.

    0 讨论(0)
  • 2020-12-14 00:47

    update typescript@2.0.0 and you can map the same webpack aliases on tsconfig.json by adding:

    "compilerOptions": {
        "baseUrl": "./",
        "paths": {
          "app/*": ["src/app/*"]
        }
    }
    
    0 讨论(0)
  • 2020-12-14 00:48

    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

    0 讨论(0)
提交回复
热议问题