首页 > 解决方案 > 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.jsonortsconfig.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 代码(内部人员)不起作用。

标签: reactjstypescriptvisual-studio-codenext.jsjsx

解决方案


对我有用的是:

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"
    }

推荐阅读