Description
In Dart 3.5.4 (stable)
, imports accepts non Dart files
Setup
Create a new Dart project using dart create dart_puzzler
Project will contain 2 dart files
|
|-- bin
| |-- dart_puzzler.dart
|-- lib
| |-- dart_puzzler.dart
With bin/dart_puzzler.dart
containing
import 'package:dart_puzzler/dart_puzzler.dart' as dart_puzzler;
void main(List<String> arguments) {
print('Hello world: ${dart_puzzler.calculate()}!');
}
And lib/dart_puzzler.dart
containing
int calculate() {
return 6 * 7;
}
Observed behavior
Create a new file lib/to_import
omitting the extension and add some dart content
int calculate() {
return 2 + 2;
}
Now replace the import in bin/dart_puzzler.dart
by
import 'package:dart_puzzler/to_import' as dart_puzzler;
It works with no warning/error.
The code can be run using dart run bin/dart_puzzler.dart
Strange, but why not. Imported file contains dart code so it can be ok I guess ?
2nd observed behavior
Create a Kotlin file lib/kotlin_file.kt
with the following content
fun calculate(): Int {
return 2 + 2
}
Now replace the import in bin/dart_puzzler.dart
by
import 'package:dart_puzzler/kotlin_file.kt' as dart_puzzler;
The dart code accepts the import without any warning/error.
Try to execute the code using dart run bin/dart_puzzler.dart
Fortunately it fails with many errors on the kotlin syntax which is normal.
But no error is raised on the import itself.
The problem
Dart seems to accept any file in the import directive and tries to parse the file content as Dart code no matter the language of the written code.
This can lead to unexpected behavior with some languages getting similar syntax as Dart like Java. In Some cases, Dart can successfully execute Java code with Dart interpretation.
Expected behavior
Should Dart accept non Dart files in imports ?
Should we get an error like Only Dart files can be imported
?