reactjs - VS Code 绝对路径使用 js/tsconfig.json 自动完成和点击查看定义
问题描述
据我所知,有两个步骤可以使绝对路径正常工作,即编译和代码编辑器。
我开始使用的编译部分babel-plugin-module-resolver
。我看到的大多数建议的另一个选项是使用 webpack 解析别名:
https://webpack.js.org/configuration/resolve/#resolve-extensions,但我无法让它工作。
.babelrc
"plugins": [
["module-resolver", {
"root": ["./"],
"alias": {
"@Components": "./components",
"@Context": "./context",
}
}]
使用它,import Context from '@Context/context'
编译就好了。
具有自动完成和点击查看定义的编辑器部分不想工作。我使用映射接近了 path-intellisense 扩展:
https://marketplace.visualstudio.com/items?itemName=christian-kohler.path-intellisense,但它仅适用于.js
您无法单击以转到定义的文件。
我认为我尝试过大约五十种不同变体的另一个解决方案是使用jsconfig.json
ortsconfig.json
并添加baseUrl
& paths
。
{
"compilerOptions": {
"baseUrl": ".",
"jsx": "preserve", // have also tried "react" and without
"paths": {
"components/*": ["components/*"],
}
}
}
当前文件夹结构
.
├── jsconfig.json
├── tsconfig.json
├── components/
├── context/
│ └── context.tsx
├── pages/
│ └── index.jsx
当前的 tsconfig.json 编译器选项
"compilerOptions": {
"target": "es5",
"lib": [
"dom",
"dom.iterable",
"esnext"
],
"allowJs": true,
"skipLibCheck": true,
"strict": false,
"forceConsistentCasingInFileNames": true,
"noEmit": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "preserve"
},
}
我正在重写打字稿,所以目前大多数文件是.jsx
但有些是.tsx
.
任何帮助将不胜感激!
编辑 1:我也尝试禁用所有扩展并尝试另一个 vs 代码(内部人员)不起作用。
解决方案
对我有用的是:
jsconfig.json
(我认为这是重要的部分)
{
"compilerOptions": {
...
"jsx": "react-jsx",
...
}
}
.eslintrc
...
"settings": {
"import/resolver": {
"node": {
"extensions": [".js", ".jsx"]
}
}
}
...
.babelrc
{
"presets": ["next/babel"],
"plugins": [
[
"module-resolver",
{
"root": ["./"],
"alias": {
"src": "./src"
}
}
]
]
}
settings.json
"path-intellisense.mappings": {
"src": "${workspaceRoot}/src"
}
推荐阅读
- javascript - 有没有办法在 Modal 中制作大小合适且功能强大的 FlatList?
- html - 如何使用纯 CSS 在不同区域做不同的(自定义)滚动条?
- scala - 如何开始调试“http 服务器在为 1 个未完成请求提供响应之前意外关闭了连接”
- java - 我应该如何正确退出这个while循环
- python-3.x - 是否有一种简单的 Python 3 方法可以像在 Java 中一样进行并行 for 循环?
- python - 如何使用正则表达式从列表中填充字典?
- angular - 从 Angular 中的 node_modules 预加载样式表
- firebase - 尝试从 Firebase 获取令牌时出现“EMAIL_NOT_FOUND”错误
- visual-studio - Visual Studio 2019 重命名重构在更新后不起作用
- node.js - 通过邮递员将数据插入多个表中