Flutter Export Dart file 자동생성

ENOOSOFT·2024년 8월 28일
  • lib 폴더의 하위 폴더에 폴더명.dart 파일을 만들고 export 구문을 활용하면 파일마다 너저분한 import 를 간소화 할 수 있다. 때때로 이 export-dart-file 을 한번에 만들 경우가 있다. 이때 사용할 수 있는 간단한 유틸리티 프로그램을 만들었다.
  • 프로젝트 루트(pubspec.yaml 파일 위치)에 export_leaves.dart 파일을 새로 만들고 아래 소스를 저장한다.
// ignore_for_file: avoid_print

import 'dart:io';

Future<void> main(List<String> args) async {
  exitCondition(args.isEmpty, 'Usage: dart export_leaves.dart [Dir in "lib"]');
  String folder = args[0].replaceAll('\\', '/');
  final currentDirSlash =
      '${Directory.current.path.replaceAll('\\', '/')}/lib/';
  String path = '$currentDirSlash$folder';
  Directory dir = Directory(path);

  exitCondition(!dir.existsSync(), 'Error: $path does not exist.');

  print('\nRun print_export in $currentDirSlash$folder\n');
  StringBuffer passed = StringBuffer();
  StringBuffer exported = StringBuffer();
  dir.list(recursive: true).listen(
    (FileSystemEntity entity) {
      if (entity is File) {
        String filePath = entity.path.replaceAll('\\', '/');
        String onlyFileName = filePath.split('/').last.replaceAll('.dart', '');
        int lastSlash = filePath.lastIndexOf('/');
        String onlyFolderName = filePath.substring(0, lastSlash);
        if (onlyFolderName.endsWith('/$onlyFileName')) {
          passed.write(
              '  - Passed: $onlyFileName.dart seems export-dart-file.\n');
        }
        if (filePath.endsWith('.dart') &&
            !filePath.endsWith('.g.dart') &&
            !filePath.endsWith('.freezed.dart') &&
            !filePath.endsWith('/$folder.dart') &&
            !onlyFolderName.endsWith('/$onlyFileName')) {
          String dartFileName = filePath.split('/$folder/').last;
          exported.write("export '$dartFileName';\n");
        }
      }
    },
    onDone: () {
      var exportFileName = folder.split('/').last;
      File file = File('$currentDirSlash$folder/$exportFileName.dart');
      file.writeAsStringSync(exported.toString());
      print(exported.toString());
      print(passed.toString());
      print('Exported to $currentDirSlash$folder/$exportFileName.dart');
    },
  );
}

void exitCondition(condition, message) {
  if (condition) {
    print(message);
    exit(1);
  }
}
  • 아래와 같이 실행하면 폴더명/폴더명.dart 형태로 export-dart-file 이 만들어진다.
dart export_leaves.dart [lib 폴더 아래 폴더명] 
  • export-dart-file 을 다른 dart 파일에서 import 하면 해당 폴더 파일들이 한번에 import 되어 편리하다.
profile
Tiny coder

0개의 댓글