我正在使用 create-react-app
+ typescript ,我想添加绝对路径。
我正在努力达到可以使用绝对路径的程度,如下所示:
而不是 import x from '../../../components/shell/shell'
使用 import x from '@components/shell/shell'
;
这是 tsconfig.json 文件:
{
"extends": "./paths.json",
"compilerOptions": {
"target": "es5",
"lib": [
"dom",
"dom.iterable",
"esnext"
],
"allowJs": true,
"baseUrl": "src",
"skipLibCheck": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "react"
},
"include": [
"src"
]
}
我正在使用扩展文件作为路径,因为出于某种原因
npm start
覆盖文件。也是如此路径.json 文件:
{
"compilerOptions": {
"baseUrl": "./src",
"paths": {
"@": ["./src"],
"@components/*": ["components/*]"
}
}
}
我也有一个 .env 文件:
NODE_PATH=src
我安装了
react-app-rewire
所以我可以配置路径,我的 config-ovverrides.js 文件如下所示:
module.exports = {
paths: function(paths, env) {
// ...add your paths config
return paths;
}
};
我坚持连接所有的点,它不起作用,我仍然看不到我需要做什么才能配置 webpack 路径对象;
我如何在 cra、ts 和 rewire 中实现路径?
最佳答案
您可以使用 解决它5 简单步骤没有弹出 :
步骤 1 :将 react-app-rewired 添加到您的 devDependencies
中.yarn add -D react-app-rewired
或 npm intall react-app-rewired --save-dev
步骤 2 : 安装后,您就可以更改package.json
默认 ReactsJS 脚本为:
"scripts": {
"start": "react-app-rewired start",
"build": "react-app-rewired build",
"test": "react-app-rewired test",
"eject": "react-app-rewired eject"
}
步骤 3 : 创建一个名为 tsconfig.paths.json
的新文件在根路径上,内容如下:{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"services/*": ["./src/shared/services/*"],
"interfaces/*": ["./src/shared/interfaces/*"]
}
}
}
提示 1 :您可以选择要使用的路径,例如:@services, @interface, @src, ~, @, etc
只需更改里面的 key "paths": {}
同样适用于它的值:["src/shared/services/"], ["src/shared/interfaces/"], ["src/*"]
,这里使用相对路径。第 4 步 : 进
tsconfig.json
, 之前 "compilerOptions"
您需要扩展 tsconfig.paths.json
你刚刚创建。像这样:
{
"extends": "./tsconfig.paths.json",
...//rest of file infos compilerOptions, include... whatever
}
步骤 5 : 创建一个新文件 config-overrides.js
,在其上添加您的别名和相对路径:const path = require('path');
module.exports = function override(config) {
config.resolve = {
...config.resolve,
alias: {
...config.alias,
'services': path.resolve(__dirname, 'src/shared/services'),
'interfaces': path.resolve(__dirname, 'src/shared/interfaces')
},
};
return config;
};
提示 2 :如果您使用的是 eslint
,记得有一个.eslintignore
文件并添加 config-overrides.js
其中。重启你的 IDE 或文本编辑器,在我的例子中是 VSCode。
它是 完毕! 现在只需运行
yarn start
或 npm run start
关于reactjs - 带有 react、react-app-rewire 和 typescript 的绝对路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59544950/