如果我使用用 typescript 配置的绝对路径,它就不起作用。在 tsconfig 文件中添加配置后,我可以通过单击组件导航到 vscode 中的文件。但项目没有运行。如果我的配置有任何问题,请帮助我。
tsconfig.json
{
"compilerOptions": {
"baseUrl": "src",
"paths": {
"~/*": ["./*"]
},
"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"
},
"include": ["src"],
"exclude": ["node_modules", "build"]
}
这是我的主路线文件
import React from 'react';
import { Route, Routes } from 'react-router-dom';
import { Login, Movie } from '~/pages';
const AppRouter: React.FC = (props) => {
return (
<Routes>
<Route path="" element={<Movie />} />
<Route path="login" element={<Login />} />
</Routes>
);
};
export default AppRouter;
当我单击组件时,它会成功转到文件。但是当我运行该项目时。它显示错误消息
Failed to compile.
Module not found: Error: Can't resolve '~/pages' in '/Volumes/Workplace/ababa_tech_task/frontend/src/routes'
ERROR in ./src/routes/index.tsx 6:0-39
Module not found: Error: Can't resolve '~/pages' in '/Volumes/Workplace/ababa_tech_task/frontend/src/routes'
webpack compiled with 1 error
Files successfully emitted, waiting for typecheck results...
Issues checking in progress...
No issues found.
它的工作原理是这样的 ->
...
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"pages": ["src/pages"]
},
}
import React from 'react';
import { Route, Routes } from 'react-router-dom';
import { Login, Movie } from 'pages'; // pages instead of ~/pages working
const AppRouter: React.FC = (props) => {
return (
<Routes>
<Route path="" element={<Movie />} />
<Route path="login" element={<Login />} />
</Routes>
);
};
export default AppRouter;
但我不想再这样下去了。因为它会令人困惑。直接模块路径意味着来自node_modules,我想保留 ~/* 这意味着来自 src 文件夹
我使用了其他带有react-rewired-app的项目,该项目有效。但我不想这样做。
最佳答案
你必须检查你的package.json中是否有"type": "module"
,因为那么你需要编写ext。在您导入的每个文件中:
import { Login, Movie } from '~/pages.tsx';
如果是这种情况,您只需删除 "type": "module"
关于javascript - 绝对路径不适用于使用 typescript 创建 react 应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73370209/