如何让VS Code在NPM工作区跳转至源码而非dist文件?
问题描述
我用NPM工作区搭建了一个monorepo,结构如下:
- packages -- common --- src ---- components -- app1 -- app2
common包包含公共React组件,供app1和app2调用。目前跨工作区引用的方式是先构建common,再从构建后的dist目录导入:
// app1 中的示例代码 import { CommonComponent } from 'common/dist'; function App() { return <CommonComponent />; }
现在遇到两个VS Code相关的问题:
- Cmd+点击
CommonComponent(转到定义)时,会跳转到common/dist/src/components/CommonComponent.d.ts,希望直接跳转到原始源码文件common/src/components/CommonComponent.tsx。 - 在
CommonComponent.tsx中,Cmd+点击组件定义无法看到引用结果(因为实际引用的是dist版本),希望能显示所有对dist版本的引用。
我清楚这属于非常规需求,但因为是本地包,能接受这种设置。IntelliJ WebStorm已支持该功能,想知道VS Code怎么实现。
补充配置信息
项目根目录.eslintrc(所有工作区继承该配置)
{ "settings": { "import/resolver": { "node": { "extensions": [".ts", ".tsx", ".js"] }, "typescript": { "projects": [ "packages/*/tsconfig.json", "packages/*/*/tsconfig.json" ] } } }, "env": { "browser": true, "es2021": true, "jest": true }, "extends": ["plugin:react/recommended", "airbnb"], "parser": "@typescript-eslint/parser", "parserOptions": { "ecmaFeatures": { "jsx": true }, "ecmaVersion": 12, "sourceType": "module" }, "plugins": ["react", "@typescript-eslint"], "rules": [...] }
各工作区的tsconfig.json
{ "compilerOptions": { "target": "es5", "lib": ["dom", "dom.iterable", "esnext"], "baseUrl": "./src", "allowJs": true, "skipLibCheck": true, "esModuleInterop": true, "allowSyntheticDefaultImports": true, "strict": true, "forceConsistentCasingInFileNames": true, "noFallthroughCasesInSwitch": true, "module": "esnext", "moduleResolution": "node", "resolveJsonModule": true, "isolatedModules": true, "noEmit": true, "jsx": "react-jsx" }, "include": ["src"] }
解决方法
1. 配置TypeScript路径映射,实现直接跳转到源码
在app1和app2的tsconfig.json中添加paths配置,将common/dist的引用映射到common/src:
{ "compilerOptions": { // 保留原有配置 "paths": { "common/dist/*": ["../common/src/*"] } } }
也可以在项目根目录创建统一的tsconfig.json,避免重复配置:
{ "files": [], "references": [ { "path": "./packages/common" }, { "path": "./packages/app1" }, { "path": "./packages/app2" } ], "compilerOptions": { "baseUrl": ".", "paths": { "common/dist/*": ["./packages/common/src/*"] } } }
配置后,TypeScript语言服务会优先解析源码路径,转到定义时直接跳转到.tsx原始文件。
2. 让源码文件识别dist版本的引用
修改common包的package.json,将types字段指向源码入口,同时确保构建时生成的.d.ts文件路径与源码结构一致:
// packages/common/package.json { "name": "common", "main": "./dist/index.js", "types": "./src/index.ts", // 指向源码入口 "scripts": { "build": "tsc --emitDeclarationOnly && ..." // 确保d.ts文件生成在dist/src目录下,和源码结构匹配 } }
安装tsconfig-paths包,让VS Code的TypeScript语言服务能正确解析路径映射。同时在VS Code设置中开启typescript.preferences.includePackageJsonAutoImports,确保语言服务识别本地包的路径配置。
3. 调整ESLint配置适配路径映射
在根目录.eslintrc的typescript解析器配置中添加路径映射,确保ESLint能正确识别路径:
{ "settings": { "import/resolver": { "typescript": { "projects": [ "packages/*/tsconfig.json", "packages/*/*/tsconfig.json" ], "alwaysTryTypes": true, "paths": { "common/dist/*": ["./packages/common/src/*"] } } } } }
内容的提问来源于stack exchange,提问作者Ronny Efronny
相关产品推荐
相关产品推荐

