LoginSignup
39
16

More than 3 years have passed since last update.

【TypeScript】フォルダごとにindex.tsを配置して一括import

Posted at

下記のようなディレクトリ構成のプロジェクトがあるとする。

│  main.ts
│
├─repository
│      index.ts
│      PostRepository.ts
│      UserRepository.ts
│
└─service
        index.ts
        LoggerService.ts
        PostService.ts
        UserService.ts

各フォルダにindex.tsを配置してそのフォルダ配下のmoduleをexportする。

たとえばservice/index.ts

service/index.ts
export { LoggerService } from "./LoggerService";
export { PostService } from "./PostService";
export { UserService } from "./UserService";

と記述しておく。
そうするとディレクトリトップにあるmain.tsはフォルダ名のみでimportできる。

main.ts
import { LoggerService, UserService } from './service';

const logger = new LoggerService();
const userService = new UserService();

const newUser = new User("stin_factory", 25);
userService.register(newUser);
logger.log(`${newUser.name}を新規登録しました。`);

記述が簡素化されて読みやすくなる。

39
16
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
39
16