ensureImport static method
Ensure the import statement of package with alias exists in source.
sourceにalias付きのpackageのimport文が存在することを保証します。
Implementation
static String ensureImport(
String source, {
required String alias,
required String package,
}) {
final import = 'import * as $alias from "$package";';
final existingImport = RegExp(
'^import \\* as \\w+ from "${RegExp.escape(package)}";\$',
multiLine: true,
).firstMatch(source);
if (existingImport != null) {
return source.replaceRange(
existingImport.start,
existingImport.end,
import,
);
}
final imports = RegExp(r"^import .+;$", multiLine: true).allMatches(source);
if (imports.isEmpty) {
return "$import\n$source";
}
final lastImport = imports.last;
return source.replaceRange(
lastImport.end,
lastImport.end,
"\n$import",
);
}