我正在使用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"
]
}
Run Code Online (Sandbox Code Playgroud)
我使用扩展文件作为路径,因为由于某种原因npm start覆盖了该文件。paths.json文件也是如此:
{
"compilerOptions": {
"baseUrl": "./src",
"paths": {
"@": ["./src"],
"@components/*": ["components/*]"
}
}
}
Run Code Online (Sandbox Code Playgroud)
我还有一个.env文件:
NODE_PATH=src
Run Code Online (Sandbox Code Playgroud)
我安装了react-app-rewire这样我就可以配置路径,我的config-ovverrides.js文件如下所示:
module.exports = {
paths: function(paths, env) {
// ...add your paths config
return paths;
}
};
Run Code Online (Sandbox Code Playgroud)
我坚持连接所有的点,它不起作用,我仍然看不到我需要做什么才能配置 webpack 路径对象;
我如何在 cra、ts 和 rewire 中实现路径?
小智 5
您可以使用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"
}
Run Code Online (Sandbox Code Playgroud)
步骤 3:tsconfig.paths.json在根路径上创建一个名为的新文件,内容如下:
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"services/*": ["./src/shared/services/*"],
"interfaces/*": ["./src/shared/interfaces/*"]
}
}
}
Run Code Online (Sandbox Code Playgroud)
提示 1:您可以选择要使用的路径,例如:
@services, @interface, @src, ~, @, etc只需更改里面的键即可"paths": {}
它的 value: 也是如此,这里使用相对路径。["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
}
Run Code Online (Sandbox Code Playgroud)
第 5 步:创建一个新文件config-overrides.js,在其中添加别名和相对路径:
const path = require('path');
module.exports = function override(config) {
config.resolve = {
...config.resolve,
alias: {
...config.resolve.alias,
'services': path.resolve(__dirname, 'src/shared/services'),
'interfaces': path.resolve(__dirname, 'src/shared/interfaces')
},
};
return config;
};
Run Code Online (Sandbox Code Playgroud)
提示 2:如果您正在使用eslint,请记住有一个.eslintignore文件并config-overrides.js在其中添加。
重新启动 IDE 或文本编辑器,在我的例子中是 VSCode。
完成!现在只需运行yarn start或npm run start
| 归档时间: |
|
| 查看次数: |
9394 次 |
| 最近记录: |