reactjs - 如何在反应中为所有导入设置基本路径
问题描述
在 create-react-app cli 项目中,使用下面的配置将所有导入路径设置src
为基本 url
jsconfig.json
{
"compilerOptions": {
"jsx": "react",
"baseUrl": "src/",
"paths": {
"~/*": ["./*"]
}
}
}
包.json
..
"scripts": {
"start": "react-scripts start",
"build": "react-scripts --max_old_space_size=4096 build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
我想使用这样的导入语句:
import { PanelHeader } from '@/components/panel';
而不是这个:
import { PanelHeader } from '../../../components/panel';
解决方案
通过检查CRA 上的Absolute Imports,您可以看到两件事:
(1) 设置baseUrl
为src
{
"compilerOptions": {
"baseUrl": "src"
},
"include": ["src"]
}
(2)从名为(文件夹的子文件夹)的文件夹中components/..
导入组件时使用components
src
例子 -import Button from 'components/Button';
所以,去掉@/
一部分。
推荐阅读
- c# - 如何为 fa 图标更改设置动画?
- php - 如何在 AWS 上的 Codeigniter 中使用 Websocket 实现服务器消息?一个
- c# - 存储代表的值
- python - 熊猫数据框,对滚动窗口中的任何列进行计算
- azure - 在两个受信任的域/应用程序之间解密由 asp.net core 2.1 Dataprotection API 加密的 cookie
- three.js - GLTFLoader 未定义 - THREE.js
- vue.js - 如何在 Chart Kick 中使用对数刻度?
- google-app-engine - 使用 app.yaml 从所有 url 文件名中删除 .html 以进行运行时
- c# - Blazor 客户端 - 重定向到登录页面
- flutter - 为什么不选择一个值并打印它(颤振)?