使用 WebStorm 优化 Imports

远子 •  2021年08月17日

WebStorm 支持优化 imports,简直是强迫症的福音,可以参见Optimize Imports in WebStorm

先来体验一下:

功能一:自动合并

格式化前:

import { Injectable } from '@nestjs/common';
import { HttpException } from '@nestjs/common';
import { HttpStatus } from '@nestjs/common';

格式化后:

import { HttpException, HttpStatus, Injectable } from '@nestjs/common';

功能二:单个 import 排序

格式化前:

import { Injectable, HttpException, HttpStatus } from '@nestjs/common';

格式化后:

import { HttpException, HttpStatus, Injectable } from '@nestjs/common';

功能三:多个 imports 排序

格式化前:

import { HttpException, HttpStatus, Injectable } from '@nestjs/common';
import { CreateRoleDto } from './dto/create-role.dto';
import { InjectRepository } from '@nestjs/typeorm';
import { UpdateRoleDto } from './dto/update-role.dto';
import { getConnection, Repository } from 'typeorm';
import { RoleEntity } from './entities/role.entity';

格式化后:

import { HttpException, HttpStatus, Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { getConnection, Repository } from 'typeorm';
import { CreateRoleDto } from './dto/create-role.dto';
import { UpdateRoleDto } from './dto/update-role.dto';
import { RoleEntity } from './entities/role.entity';

功能四:分组

真实项目里,imports 一般分三种:库、其他模块、本地模块。WebStorm 可以按照分组将不同的 imports 放在一起。

其他模块一般使用路径别名,下边以 ~ 指向到 src 目录为例:

格式化前:

import { HttpException, HttpStatus, Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { getConnection, Repository } from 'typeorm';
import { BaseService } from '~/core';
import { AccessService } from '~/system/access/access.service';
import { CreateRoleDto } from './dto/create-role.dto';
import { UpdateRoleDto } from './dto/update-role.dto';
import { RoleEntity } from './entities/role.entity';
import { RoleAccessEntity } from '~/system/role-access/entities/role-access.entity';
import { RoleAccessService } from '~/system/role-access/role-access.service';

格式化后:

import { HttpException, HttpStatus, Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { getConnection, Repository } from 'typeorm';
import { BaseService } from '~/core';
import { AccessService } from '~/system/access/access.service';
import { RoleAccessEntity } from '~/system/role-access/entities/role-access.entity';
import { RoleAccessService } from '~/system/role-access/role-access.service';
import { CreateRoleDto } from './dto/create-role.dto';
import { UpdateRoleDto } from './dto/update-role.dto';
import { RoleEntity } from './entities/role.entity';

如何启用

第一步,指定 Imports 规则:

image-20210817093419777

第二步:在 Save 时自动触发:

image-20210817093440916

再配合 Prettier 保存时自动格式化代码,完美~

(完)