我正在使用Webpack和Visual Studio Code,以避免以下情况:
import { AuthenticationService } from '../../../services/authentication/service';
我在webpack.config上创建了别名,所以我可以使用:
import { AuthenticationService } from 'services/authentication/service';
但是,通过这样做,Visual Code无法检测到我的代码,因此我失去了我的类的智能感知。
有没有人有解决方案,有没有办法让VS代码读取webpack.config并识别带别名的路径?
提前致谢
更新[email protected]并且您可以通过添加以下内容在tsconfig.json上映射相同的webpack别名:
"compilerOptions": {
"baseUrl": "./",
"paths": {
"app/*": ["src/app/*"]
}
}
我遇到了类似的问题。因为我使用的是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
这最终为我工作:
var path = require('path');
module.exports = {
resolve: {
alias: {
"my-module": path.resolve(__dirname, './src/my-module')
}
},
// ... other webpack options
};
{
"compilerOptions": {
"target": "es6",
"paths": {
"my-module": ["./my-module"]
}
}
}
// in foo.js
import Bar from 'my-module/bar';
Bar.quack();
您需要在jsconfig.json文件中指定paths
和baseUrl
字段。
{
"compilerOptions": {
"jsx": "react",
"target": "ES6",
"allowSyntheticDefaultImports": true,
"baseUrl": "./",
"paths": {
"~/*": ["./app/*"]
}
},
"exclude": [
"node_modules"
]
}
安装VSCode扩展PathIntellisense。
要打开您的VSCode设置文件,您可以按下命令,在macOS上(在Windows上是ctrl,),在右上角找到“一对花括号按钮”,单击它。
在我的情况下,我想使用符号@
作为路径./src
的别名。所以我将此配置添加到我的VSCode设置文件中:
"path-intellisense.mappings": {
"@": "${workspaceRoot}/src"
}
当路径应该相对于当前项目的当前根时,请使用${workspaceRoot}
。
你可以找到官方的例子here。
原始答案:
我使用VSCode扩展PathIntellisense。
在我的VSCode设置文件中配置此setting。
现在VSCode可以识别带别名的路径。