diff --git a/CHANGELOG.md b/CHANGELOG.md index ee23d39..1fc26c7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,7 @@ ## 4.9.0 * Add `Library.generatedByComment` to support emitting 'generated by' comments. +* Support emitting an unnamed library with annotations. ## 4.8.0 diff --git a/lib/src/emitter.dart b/lib/src/emitter.dart index 617cb7b..99c91e4 100644 --- a/lib/src/emitter.dart +++ b/lib/src/emitter.dart @@ -512,13 +512,16 @@ class DartEmitter extends Object } } + for (var a in spec.annotations) { + visitAnnotation(a, output); + } if (spec.name != null) { - for (var a in spec.annotations) { - visitAnnotation(a, output); - } output.write('library ${spec.name!};'); } else if (spec.annotations.isNotEmpty) { - throw StateError('a library name is required for annotations'); + // An explicit _unnamed_ library directive is only required if there are + // annotations or doc comments on the library (though doc comments are not + // currently supported in code_builder). + output.write('library;'); } final directives = [...allocator.imports, ...spec.directives]; diff --git a/test/specs/library_test.dart b/test/specs/library_test.dart index a2974fe..6b7fdea 100644 --- a/test/specs/library_test.dart +++ b/test/specs/library_test.dart @@ -277,17 +277,19 @@ void main() { ); }); - test('should error on unnamed library with annotations', () { + test('should emit an unnamed library source file with annotations', () { expect( - () { - Library( - (b) => b - ..annotations.add( - refer('JS', 'package:js/js.dart').call([]), - ), - ).accept(DartEmitter()); - }, - throwsStateError, + Library( + (b) => b + ..annotations.add( + refer('JS', 'package:js/js.dart').call([]), + ), + ), + equalsDart(r''' + @JS() + library; + import 'package:js/js.dart'; + ''', DartEmitter(allocator: Allocator())), ); }); });