波浪线 ~/ 一种优雅的 JS import 路径简化写法

本文对提升您的编程开发能力毫无帮助。仅供代码洁癖患者食用。

在大型前端项目中,用文件夹来组织代码很常见。但是 JS 的引用是基于相对路径的,一旦路径到达一定深度,就会出现非常长的路径:

import Button from '../../../../components/button';
import Factory from '../../../../types/Factory';

这样会带来两个烦恼:

  1. 要精确的计算 ../.. 的层级数量是一项很耗精力的事情。
  2. 如果相对路径很长,就会折行,让代码更难阅读。

阿里系的项目中,从 ice.js 开始引入了一种用 @/ 简化的写法(基于 Babel/TypeScript 的路径别名):

import Button from '@/components/button';
import Factory from '@/types/Factory';

这种写法解决了以上的两个问题,但是引入了一些新的问题。

首先是 @/ 容易和 npm 包的 org 名混淆:

import DateTime from '@/types/date-time';
import DateTimer from '@types/date-timer';

再有就是 VS Code 的 import 自动排序功能(默认关闭)会将 @/ 的导入置于最前:绝对路径导入 -> npm 包导入 -> 相对路径导入。

// VS Code 自动排序结果
import NiceButton from '@/components/button';
import DataList from '@/types';
import { Button } from '@mui/material';
import { ReactNode } from 'react';
import { useLocalStorage } from 'react-hooks';
import CoolHeader from './components/header';
import Container from './Container';

这显然不是很合理。最理想的顺序应该是:npm 包导入 -> 绝对路径导入 -> 相对路径导入。

Remix 项目提供了一种新的写法 ~/ 这种写法 Linux 和 macOS 用户应该很熟悉,是用户目录的简写。Remix 这里借用了一下,完美解决了以上两个问题。

// VS Code 自动排序结果
import { Button } from '@mui/material';
import { ReactNode } from 'react';
import { useLocalStorage } from 'react-hooks';
import NiceButton from '~/components/button';
import DataList from '~/types';
import CoolHeader from './components/header';
import Container from './Container';

TypeScript 项目配置也很方便:

{
  "compilerOptions": {
    "paths": {
      "~/*": ["src/*"]
    }
  }
}

我认为这是目前最好的解决方案。

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据