feat(codegen): correctly print type-only imports/exports (#2993)

This commit is contained in:
Dunqing 2024-04-15 18:33:02 +08:00 committed by GitHub
parent 82e00bc951
commit fd5002bc51
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 21 additions and 0 deletions

View file

@ -724,6 +724,9 @@ impl<'a, const MINIFY: bool> Gen<MINIFY> for ImportDeclaration<'a> {
fn gen(&self, p: &mut Codegen<{ MINIFY }>, ctx: Context) {
p.add_source_mapping(self.span.start);
p.print_str(b"import ");
if p.options.enable_typescript && self.import_kind.is_type() {
p.print_str(b"type ");
}
if let Some(specifiers) = &self.specifiers {
if specifiers.is_empty() {
p.print(b'\'');
@ -770,6 +773,10 @@ impl<'a, const MINIFY: bool> Gen<MINIFY> for ImportDeclaration<'a> {
p.print(b'{');
}
if p.options.enable_typescript && spec.import_kind.is_type() {
p.print_str(b"type ");
}
let imported_name = match &spec.imported {
ModuleExportName::Identifier(identifier) => {
identifier.gen(p, ctx);
@ -842,6 +849,9 @@ impl<'a, const MINIFY: bool> Gen<MINIFY> for ExportNamedDeclaration<'a> {
return;
}
p.print_str(b"export ");
if p.options.enable_typescript && self.export_kind.is_type() {
p.print_str(b"type ");
}
match &self.declaration {
Some(decl) => decl.gen(p, ctx),
None => {
@ -866,6 +876,9 @@ impl<'a, const MINIFY: bool> Gen<MINIFY> for ExportNamedDeclaration<'a> {
impl<'a, const MINIFY: bool> Gen<MINIFY> for ExportSpecifier<'a> {
fn gen(&self, p: &mut Codegen<{ MINIFY }>, ctx: Context) {
if p.options.enable_typescript && self.export_kind.is_type() {
p.print_str(b"type ");
}
self.local.gen(p, ctx);
if self.local.name() != self.exported.name() {
p.print_str(b" as ");
@ -892,6 +905,9 @@ impl<'a, const MINIFY: bool> Gen<MINIFY> for ExportAllDeclaration<'a> {
return;
}
p.print_str(b"export ");
if p.options.enable_typescript && self.export_kind.is_type() {
p.print_str(b"type ");
}
p.print(b'*');
if let Some(exported) = &self.exported {

View file

@ -162,4 +162,9 @@ fn typescript() {
test_ts("let x: string['length'] = 123;", "let x: string['length'] = 123;\n", false);
test_ts("function isString(value: unknown): asserts value is string {\n\tif (typeof value !== 'string') {\n\t\tthrow new Error('Not a string');\n\t}\n}", "function isString(value: unknown): asserts value is string {\n\tif (typeof value !== 'string') {\n\t\tthrow new Error('Not a string');\n\t}\n}\n", false);
// type-only imports/exports
test_ts("import type { Foo } from 'foo';", "import type {Foo} from 'foo';\n", false);
test_ts("import { Foo, type Bar } from 'foo';", "import {Foo,type Bar} from 'foo';\n", false);
test_ts("export { Foo, type Bar } from 'foo';", "export { Foo, type Bar } from 'foo';", false);
}