Strip type-only imports (#641)

Fixes #640
This commit is contained in:
kdy1 2020-02-09 11:35:33 +00:00
parent add63826bd
commit f8c358c9ac
2 changed files with 30 additions and 11 deletions

View File

@ -2,12 +2,11 @@ use crate::{
pass::Pass,
util::{prepend_stmts, var::VarCollector, ExprFactory},
};
use hashbrown::HashMap;
use swc_atoms::{js_word, JsWord};
use swc_common::{
util::move_map::MoveMap, Fold, FoldWith, Spanned, SyntaxContext, Visit, VisitWith, DUMMY_SP,
};
use fxhash::FxHashMap;
use swc_atoms::js_word;
use swc_common::{util::move_map::MoveMap, Fold, FoldWith, Spanned, Visit, VisitWith, DUMMY_SP};
use swc_ecma_ast::*;
use swc_ecma_utils::Id;
/// Strips type annotations out.
pub fn strip() -> impl Pass {
@ -19,6 +18,8 @@ struct Strip {
non_top_level: bool,
scope: Scope,
phase: Phase,
was_side_effect_import: bool,
}
#[derive(Debug, Clone, Copy)]
@ -39,8 +40,8 @@ impl Default for Phase {
#[derive(Default)]
struct Scope {
decls: HashMap<(JsWord, SyntaxContext), DeclInfo>,
imported_idents: HashMap<(JsWord, SyntaxContext), DeclInfo>,
decls: FxHashMap<Id, DeclInfo>,
imported_idents: FxHashMap<Id, DeclInfo>,
}
#[derive(Debug, Default)]
@ -207,9 +208,18 @@ impl Fold<Vec<ModuleItem>> for Strip {
// Second pass
let mut stmts = Vec::with_capacity(items.len());
for item in items {
self.was_side_effect_import = false;
match item {
ModuleItem::Stmt(Stmt::Empty(..)) => continue,
ModuleItem::ModuleDecl(ModuleDecl::Import(i)) => {
let i = i.fold_with(self);
if self.was_side_effect_import || !i.specifiers.is_empty() {
stmts.push(ModuleItem::ModuleDecl(ModuleDecl::Import(i)));
}
}
ModuleItem::ModuleDecl(ModuleDecl::ExportDecl(ExportDecl {
decl: Decl::TsEnum(e),
..
@ -476,6 +486,8 @@ impl Fold<ImportDecl> for Strip {
import
}
Phase::DropImports => {
self.was_side_effect_import = import.specifiers.is_empty();
import.specifiers.retain(|s| match *s {
ImportSpecifier::Default(ImportDefault { ref local, .. })
| ImportSpecifier::Specific(ImportSpecific { ref local, .. }) => {

View File

@ -80,8 +80,7 @@ to!(
issue_179_01,
"import {Types} from 'other';
const a: Types.foo = {};",
"import 'other';
const a = {};"
"const a = {};"
);
to!(
@ -166,7 +165,6 @@ import { PlainObject } from 'simplytyped';
const dict: PlainObject = {};
",
"
import 'simplytyped';
const dict = {};"
);
@ -179,7 +177,6 @@ import { PlainObject } from 'simplytyped';
const dict: PlainObject = {};
",
"
import 'simplytyped';
const dict = {};"
);
@ -314,3 +311,13 @@ test!(
}));",
ok_if_code_eq
);
test!(
::swc_ecma_parser::Syntax::Typescript(Default::default()),
|_| strip(),
issue_640,
"import { Handler } from 'aws-lambda';
export const handler: Handler = async (event, context) => {};",
"export const handler = async (event, context) => {};",
ok_if_code_eq
);