dart-lang / language

Design of the Dart language
Other
2.65k stars 202 forks source link

Add syntactic sugar for package imports #3929

Open MichaelFenwick opened 2 months ago

MichaelFenwick commented 2 months ago

In Dart, it's extremely common to see imports that look like this

import 'package:epubx/epubx.dart';
import 'package:path/path.dart' as path;
import 'package:quiver/collection.dart';
import 'package:web/web.dart';
import 'package:xml/xml.dart';

The repetition in there should be plain to see. As it is the case that it's standard for libraries to put the primarily intended import in a file with the same name as the package, I suggest adding syntactic sugar where import 'package:foo' would be treated the same as import 'package:foo/foo.dart'. Under this proposed change, the current syntax would remain valid.

With this feature, the example above would instead look like

import 'package:epubx';
import 'package:path' as path;
import 'package:quiver/collection.dart';
import 'package:web';
import 'package:xml';

Beyond being less typing and less reading, and generally looking cleaner, I believe this sugar would also make it easier to see at a glance which packages are being imported partially. It would also allow these "standard" package imports to better mirror the format of Dart SDK imports (import 'dart:async;').

Wdestroier commented 2 months ago

You may want to upvote issue #649.

lrhn commented 2 months ago

This is effectively asking for less than #649, that the URI package:foo is accepted and treated as equivalent to (or normalized to) package:foo/foo.dart.

It's not impossible. It requires adding a normalization step to package URI parsing, which adds the /foo.dart, but it should be well defined how to do that.

As in #649, a package:foo.bar.baz would normalize to package:foo.bar.baz/baz.dart, to support existing, and hypothetical future, uses of dotted package names.

I want to normalize the URI rather than having two different URIs denote the same file, because Dart library identity is defined by URI equality. Alternatively we change the rules for library identity to allow equivalences on URIs, so the compiler gets to decide when two URIs are equivalent (within reason).