首页 > 解决方案 > React 导入语句的标准方式

问题描述

我想知道是否有一种标准方法可以在反应中编写导入语句?例如,我有这个:

import React, { useState, FormEvent } from 'react';
import Avatar from '@material-ui/core/Avatar';
import {Grid, Checkbox, TextField, FormControlLabel, CssBaseline} from '@material-ui/core';
import LockOutlinedIcon from '@material-ui/icons/LockOutlined';
import { LOGIN } from '../../graphql/mutations/login';
import { schema } from '../../helpers/validations/login';
import { Redirect } from 'react-router-dom';
import { useMutation } from '@apollo/react-hooks';
import StatusMessage from '../../helpers/statusMessages/loginMessage';
import Copyright from '../../components/copyright/copyright';
import CustomButton from '../../components/button/button';
import { ExecutionResult } from 'graphql';
import { Wrapper, StyledLink, Form, StyledTypography, StyledBox, StyledContainer} from './styles';
import { store } from '../../store';
import { useDispatch } from 'react-redux';
import SignInResponse from '../../graphql/responses/login';
import { useFormik } from 'formik';

'@material-ui/core';关于我应该单独或一起导入所有内容是否有任何规则?除了减少行数之外,它有什么不同吗?

在 react 自己的库/内容之后是否应该导入其他本地文件/函数有什么规则吗?还有其他规则/建议吗?

标签: javascriptreactjstypescriptimportmaterial-ui

解决方案


有已知的标准,其中大多数是意见而不是必须做的。我建议您查看eslint-plugin-import,因为它有大量关于导入的标准/意见列表:

  • 确保所有导入出现在其他语句之前 ([ first])
  • 确保所有导出出现在其他语句之后 ([ exports-last])
  • 报告在多个地方重复导入同一模块 ([ no-duplicates])
  • 禁止命名空间(又名“通配符” *)导入([ no-namespace])
  • extensions确保在导入路径 ([ ])中一致使用文件扩展名
  • 在模块导入顺序中强制执行约定 ([ order])
  • 在 import 语句后强制换行 ([ newline-after-import])
  • 如果模块导出单个名称 ([ prefer-default-export]) ,则首选默认导出
  • 限制模块可以拥有的最大依赖项数 ([ max-dependencies])
  • 禁止未分配的导入 ([ no-unassigned-import])
  • 禁止命名默认导出 ([ no-named-default])
  • 禁止默认导出 ([ no-default-export])
  • 禁止命名导出 ([ no-named-export])
  • 禁止匿名值作为默认导出 ([ no-anonymous-default-export])
  • 更喜欢将命名的出口组合在一个出口声明中 ([ group-exports])
  • 使用 webpackChunkName 强制执行前导注释以进行动态导入 ([ dynamic-import-chunkname])

关于顺序推荐的是:

  1. 节点“内置”模块
  2. “外部”模块
  3. “内部”模块
  4. 来自“父”目录的模块
  5. 来自相同或同级目录的“同级”模块
  6. 当前目录的“索引”

推荐阅读