让VS代码读取webpack.config并使用别名识别路径?

时间:2016-06-26 23:07:39

标签: webpack visual-studio-code

我正在使用Webpack和Visual Studio Code,以避免类似的事情:

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

我在webpack.config上创建了别名,所以我可以使用:

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

然而,通过这样做,Visual Code无法检测到我的代码,因此我失去了我的类的知识产权。

有没有人有这方面的解决方案,有没有办法让VS代码读取webpack.config并识别带别名的路径?

提前致谢

5 个答案:

答案 0 :(得分:12)

更新typescript@2.0.0,您可以通过添加以下内容在tsconfig.json上映射相同的webpack别名:

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

答案 1 :(得分:8)

我遇到了类似的问题。因为我使用的是javascript而不是打字稿,所以我必须创建一个jsconfig.json文件并适当地使用paths选项。

假设这样的目录结构:

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

这最终为我工作:

  1. 设置webpack解析别名:

    var path = require('path');
    module.exports = {
      resolve: {
        alias: {
          "my-module": path.resolve(__dirname, './src/my-module')
        }
      },
      // ... other webpack options
    };
    
  2. 修改src文件夹中的jsconfig.json:

    {
      "compilerOptions": {
        "target": "es6",
        "paths": {
          "my-module": ["./my-module"]
        }
      }
    }
    
  3. 使用别名:

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

答案 2 :(得分:4)

您需要在jsconfig.json文件中指定pathsbaseUrl字段。

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

请参阅path mapping documentation

答案 3 :(得分:0)

为 VSCode 使用 Path Autocomplete 扩展

对我来说它比 PathIntellisense 更好。

只需添加配置:

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

Work screenshot

答案 4 :(得分:-1)

我使用VSCode扩展名PathIntellisense

在我的VSCode设置文件中配置此setting

现在VSCode可以识别具有别名的路径。