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

问题描述 投票:29回答:4

我正在使用Webpack和Visual Studio Code,以避免以下情况:

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

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

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

但是,通过这样做,Visual Code无法检测到我的代码,因此我失去了我的类的智能感知。

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

提前致谢

webpack visual-studio-code
4个回答
15
投票

更新[email protected]并且您可以通过添加以下内容在tsconfig.json上映射相同的webpack别名:

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

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

5
投票

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

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

path mapping documentation


1
投票

安装VSCode扩展PathIntellisense

要打开您的VSCode设置文件,您可以按下命令,在macOS上(在Windows上是ctrl,),在右上角找到“一对花括号按钮”,单击它。

在我的情况下,我想使用符号@作为路径./src的别名。所以我将此配置添加到我的VSCode设置文件中:

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

当路径应该相对于当前项目的当前根时,请使用${workspaceRoot}

你可以找到官方的例子here


原始答案:

我使用VSCode扩展PathIntellisense

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

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

© www.soinside.com 2019 - 2024. All rights reserved.