Skip to content

Commit

Permalink
fix: ✅ ts annotated declare variable treat as top level variable (#1682)
Browse files Browse the repository at this point in the history
* test: ✅ add ts declare annotated variable as top level

* refactor: 🎨 mv clean syntax context to visitors folder

* fix: 🐛 strip ts/tsx first, then do normal transform
  • Loading branch information
stormslowly authored Nov 13, 2024
1 parent e8b9a68 commit dd22d96
Show file tree
Hide file tree
Showing 7 changed files with 72 additions and 32 deletions.
62 changes: 45 additions & 17 deletions crates/mako/src/build/transform.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,11 @@ use std::sync::Arc;
use anyhow::Result;
use swc_core::base::try_with_handler;
use swc_core::common::errors::HANDLER;
use swc_core::common::GLOBALS;
use swc_core::common::{Mark, GLOBALS};
use swc_core::css::ast::{AtRule, AtRulePrelude, ImportHref, Rule, Str, Stylesheet, UrlValue};
use swc_core::css::compat::compiler::{self, Compiler};
use swc_core::css::{compat as swc_css_compat, prefixer, visit as swc_css_visit};
use swc_core::ecma::ast::Module;
use swc_core::ecma::preset_env::{self as swc_preset_env};
use swc_core::ecma::transforms::base::feature::FeatureFlag;
use swc_core::ecma::transforms::base::fixer::paren_remover;
Expand All @@ -16,7 +17,7 @@ use swc_core::ecma::transforms::compat::reserved_words;
use swc_core::ecma::transforms::optimization::simplifier;
use swc_core::ecma::transforms::optimization::simplify::{dce, Config as SimplifyConfig};
use swc_core::ecma::transforms::proposal::decorators;
use swc_core::ecma::visit::{Fold, VisitMut};
use swc_core::ecma::visit::{Fold, VisitMut, VisitMutWith};

use crate::ast::css_ast::CssAst;
use crate::ast::file::File;
Expand All @@ -29,6 +30,7 @@ use crate::module::ModuleAst;
use crate::plugin::PluginTransformJsParam;
use crate::plugins::context_module::ContextModuleVisitor;
use crate::visitors::amd_define_overrides::amd_define_overrides;
use crate::visitors::clean_ctxt::clean_syntax_context;
use crate::visitors::css_assets::CSSAssets;
use crate::visitors::css_flexbugs::CSSFlexbugs;
use crate::visitors::css_px2rem::Px2Rem;
Expand Down Expand Up @@ -75,6 +77,22 @@ impl Transform {
|| file.extname == "ts"
|| file.extname == "tsx";

if is_tsx || is_ts {
if is_tsx {
strip_unresolved_tsx(
&mut ast.ast,
context.clone(),
cm.clone(),
)
}
// strip should be ts only
// since when use this in js, it will remove all unused imports
// which is not expected as what webpack does
if is_ts {
strip_unresolved_ts(&mut ast.ast);
}
}

// visitors
let mut visitors: Vec<Box<dyn VisitMut>> = vec![
Box::new(resolver(
Expand All @@ -94,21 +112,7 @@ impl Transform {
}),
Box::new(WorkerModule::new(unresolved_mark)),
];
if is_tsx {
visitors.push(Box::new(tsx_strip(
cm.clone(),
context.clone(),
top_level_mark,
unresolved_mark,
)))
}
// strip should be ts only
// since when use this in js, it will remove all unused imports
// which is not expected as what webpack does
if is_ts {
visitors
.push(Box::new(ts_strip(unresolved_mark, top_level_mark)));
}

// named default export
if context.args.watch && !file.is_under_node_modules && is_jsx {
visitors.push(Box::new(DefaultExportNamer::new()));
Expand Down Expand Up @@ -347,3 +351,27 @@ fn import_url_to_href(ast: &mut Stylesheet) {
}
});
}

fn strip_unresolved_ts(ast: &mut Module) {
let unresolved_mark = Mark::new();
let top_level_mark = Mark::new();

ast.visit_mut_with(&mut resolver(unresolved_mark, top_level_mark, true));
ast.visit_mut_with(&mut ts_strip(unresolved_mark, top_level_mark));

ast.visit_mut_with(&mut clean_syntax_context());
}

fn strip_unresolved_tsx(
ast: &mut Module,
context: Arc<Context>,
cm: Arc<swc_core::common::SourceMap>,
) {
let unresolved_mark = Mark::new();
let top_level_mark = Mark::new();

ast.visit_mut_with(&mut resolver(unresolved_mark, top_level_mark, true));
ast.visit_mut_with(&mut tsx_strip(cm, context, top_level_mark, unresolved_mark));

ast.visit_mut_with(&mut clean_syntax_context());
}
17 changes: 3 additions & 14 deletions crates/mako/src/plugins/tree_shaking/shake/module_concatenate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,10 @@ use std::sync::Arc;
use concatenated_transformer::ConcatenatedTransform;
use external_transformer::ExternalTransformer;
use swc_core::common::util::take::Take;
use swc_core::common::{SyntaxContext, GLOBALS};
use swc_core::common::GLOBALS;
use swc_core::ecma::transforms::base::hygiene::hygiene;
use swc_core::ecma::transforms::base::resolver;
use swc_core::ecma::visit::{as_folder, Fold, VisitMut, VisitMutWith};
use swc_core::ecma::visit::VisitMutWith;

use self::concatenate_context::EsmDependantFlags;
use self::utils::uniq_module_prefix;
Expand All @@ -27,6 +27,7 @@ use crate::plugins::tree_shaking::module::{AllExports, ModuleSystem, TreeShakeMo
use crate::plugins::tree_shaking::shake::module_concatenate::concatenate_context::{
ConcatenateContext, RuntimeFlags,
};
use crate::visitors::clean_ctxt::clean_syntax_context;
use crate::{mako_profile_function, mako_profile_scope};

pub fn optimize_module_graph(
Expand Down Expand Up @@ -446,18 +447,6 @@ struct ConcatenateConfig {
externals: HashMap<ModuleId, EsmDependantFlags>,
}

struct CleanSyntaxContext;

pub fn clean_syntax_context() -> impl VisitMut + Fold {
as_folder(CleanSyntaxContext {})
}

impl VisitMut for CleanSyntaxContext {
fn visit_mut_syntax_context(&mut self, ctxt: &mut SyntaxContext) {
*ctxt = SyntaxContext::empty();
}
}

impl ConcatenateConfig {
fn new(root: ModuleId) -> Self {
Self {
Expand Down
1 change: 1 addition & 0 deletions crates/mako/src/visitors.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
pub(crate) mod amd_define_overrides;
pub(crate) mod async_module;
pub(crate) mod clean_ctxt;
pub(crate) mod common_js;
pub(crate) mod css_assets;
pub(crate) mod css_dep_analyzer;
Expand Down
14 changes: 14 additions & 0 deletions crates/mako/src/visitors/clean_ctxt.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
use swc_core::common::SyntaxContext;
use swc_core::ecma::visit::{as_folder, Fold, VisitMut};

struct CleanSyntaxContext;

pub fn clean_syntax_context() -> impl VisitMut + Fold {
as_folder(CleanSyntaxContext {})
}

impl VisitMut for CleanSyntaxContext {
fn visit_mut_syntax_context(&mut self, ctxt: &mut SyntaxContext) {
*ctxt = SyntaxContext::empty();
}
}
1 change: 1 addition & 0 deletions e2e/fixtures/config.define/expect.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
const { parseBuildResult, injectSimpleJest } = require("../../../scripts/test-utils");
const { distDir } = parseBuildResult(__dirname);
const path = require("path");

injectSimpleJest()
require(path.join(distDir, 'index.js'));
Expand Down
3 changes: 2 additions & 1 deletion e2e/fixtures/config.define/mako.config.json
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
]
}
},
"III": "{\"v\": 1}"
"III": "{\"v\": 1}",
"FOO": "\"bar\""
}
}
6 changes: 6 additions & 0 deletions e2e/fixtures/config.define/src/index.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
process.env.NODE_ENV;

declare var FOO: string;

it("defined string value should be right", () => {
expect(AAA).toEqual("aaa")
});
Expand Down Expand Up @@ -39,3 +41,7 @@ it("defined stringified object value should be right", () => {
expect(III).toEqual({ v: 1 })
});


it("should replace ts declare shallowed value", ()=>{
expect(FOO).toEqual("bar")
});

0 comments on commit dd22d96

Please sign in to comment.