我通过以下方式在我的 tsconfig.json 中配置了 tsconfig-paths 版本 3.9.0:
tsconfig.json:
{
"compilerOptions": {
"target": "es5",
"lib": [
"dom",
"dom.iterable",
"esnext"
],
"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",
"baseUrl": "src",
"paths": {
"@models/*": ["./models/*"],
"@api/*": ["./api/*"],
"@pages/*": ["./pages/*"],
"@utils/*": ["./utils/*"]
}
}
}
包.json:
{
"dependencies": {
"@testing-library/jest-dom": "^5.11.4",
"@testing-library/react": "^11.1.0",
"@testing-library/user-event": "^12.1.10",
"@types/jest": "^26.0.15",
"@types/node": "^12.0.0",
"@types/react": "^17.0.0",
"@types/react-dom": "^17.0.0",
"react": "^17.0.1",
"react-dom": "^17.0.1",
"react-scripts": "4.0.3",
"typescript": "4.1.5",
"web-vitals": "^1.0.1"
},
"scripts": {
"start": "react-scripts -r tsconfig-paths/register start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
},
"devDependencies": {
"@typescript-eslint/eslint-plugin": "4.15.2",
"@typescript-eslint/parser": "4.15.2",
"eslint": "7.11.0",
"eslint-config-airbnb": "18.2.1",
"eslint-plugin-import": "2.22.1",
"eslint-plugin-jsx-a11y": "6.4.1",
"eslint-plugin-react": "7.21.5",
"eslint-plugin-react-hooks": "4",
"tsconfig-paths": "3.9.0"
}
}
在我的 App.tsx 中,我使用在 tsconfig 中声明的绝对路径导入:
import React from 'react';
import { Test } from '@models/test.interface';
import { CONFIG } from '@api/something';
import logo from './logo.svg';
import './App.css';
function App() {
const test: Test = {
x: 10
};
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<p>
Edit
{test.x}
{CONFIG.KEY}
<code>src/App.tsx</code>
and save to reload.
</p>
<a
className="App-link"
href="https://reactjs.org"
target="_blank"
rel="noopener noreferrer"
>
Learn React
</a>
</header>
</div>
);
}
export default App;
我的界面被发现并成功编译,但我的“配置”没有。我的 CONFIG 是我导出的常量,而“测试”是一个接口。
当我只编译我的接口测试时,它完全没问题。但是当我导入我的 const CONFIG 时,它给出了这个错误:
Failed to compile.
./src/App.tsx
Module not found: Can't resolve '@api/something' in 'C:\Users\shadownet\Desktop\files_work\web-project\src'
有什么想法吗?