Make VS code read webpack.config and recognize pat

2020-02-20 06:19发布

问题:

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

import { AuthenticationService } from '../../../services/authentication/service';

I've created aliases on my webpack.config so I can use:

import { AuthenticationService } from 'services/authentication/service';

However, by doing so Visual Code is not able to detected my code and therefore I lose the intelisense for my classes.

Does anyone have a solution for that, is there a way to make VS code to read the webpack.config and recognize the path with the alias?

thanks in advance

回答1:

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

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


回答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();
    


回答3:

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



回答4:

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.