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

webpack Webpack

老丝阿飞

2020-03-24

我正在使用Webpack和Visual Studio Code,为了避免出现类似情况:

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

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

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

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

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

提前致谢

第3373篇《使VS代码读取webpack.config并使用别名识别路径?》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

3个回答
LEYTom 2020.03.24

安装VSCode扩展PathIntellisense

要打开VSCode设置文件,可以在macOS上command+ ,(在Windows上为ctrl+ ,),在右上角找到“一对大括号按钮”,然后单击它。

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

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

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

您可以在此处找到官方示例


原始答案:

I use the VSCode extension PathIntellisense .

Configure this setting in my VSCode setting file.

Now VSCode could recognize the path with the alias.

十三Sam 2020.03.24

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

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

请参阅路径映射文档

null 2020.03.24

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

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

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android