Skip to content
This repository was archived by the owner on Jul 6, 2025. It is now read-only.

Commit 015bfbb

Browse files
committed
feat(compiler): add resolveStarExports option
1 parent ed5e56c commit 015bfbb

File tree

6 files changed

+87
-53
lines changed

6 files changed

+87
-53
lines changed

compiler/mod.ts

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,7 @@ export type TransformOptions = {
3434
sourceMap?: boolean
3535
isDev?: boolean
3636
transpileOnly?: boolean
37+
resolveStarExports?: boolean
3738
bundleMode?: boolean
3839
bundleExternal?: string[]
3940
// loaders for inline styles transform
@@ -43,8 +44,8 @@ export type TransformOptions = {
4344
export type TransformResult = {
4445
code: string
4546
deps: DependencyDescriptor[]
46-
bundleStarExports?: string[]
47-
map?: string
47+
starExports: string[] | null
48+
map: string | null
4849
}
4950

5051
type InlineStyles = Record<string, { type: string, quasis: string[], exprs: string[] }>
@@ -121,7 +122,13 @@ export async function transform(url: string, code: string, options: TransformOpt
121122
}
122123

123124
const { loaders, ...transformOptions } = options
124-
let { code: jsContent, deps, map, inlineStyles, bundleStarExports } = transformSync(url, code, transformOptions)
125+
let {
126+
code: jsContent,
127+
deps,
128+
map,
129+
inlineStyles,
130+
starExports
131+
} = transformSync(url, code, transformOptions)
125132

126133
// resolve inline-style
127134
await Promise.all(Object.entries(inlineStyles as InlineStyles).map(async ([key, style]) => {
@@ -166,7 +173,7 @@ export async function transform(url: string, code: string, options: TransformOpt
166173
jsContent = jsContent.replace(`"%%${key}-placeholder%%"`, '`' + tpl + '`')
167174
}))
168175

169-
return { code: jsContent, deps, map, bundleStarExports }
176+
return { code: jsContent, deps, map, starExports }
170177
}
171178

172179
/* parse export names of the module */

compiler/src/fixer.rs

Lines changed: 8 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -60,45 +60,20 @@ impl Fold for CompatFixer {
6060
#[cfg(test)]
6161
mod tests {
6262
use super::*;
63-
use crate::swc::SWC;
64-
use std::cmp::min;
65-
use swc_common::Globals;
66-
67-
fn t(specifier: &str, source: &str, expect: &str) -> bool {
68-
let module = SWC::parse(specifier, source, None).expect("could not parse module");
69-
let (code, _) = swc_common::GLOBALS.set(&Globals::new(), || {
70-
module
71-
.apply_transform(compat_fixer_fold(), false)
72-
.expect("could not transpile module")
73-
});
74-
75-
if code != expect {
76-
let mut p: usize = 0;
77-
for i in 0..min(code.len(), expect.len()) {
78-
if code.get(i..i + 1) != expect.get(i..i + 1) {
79-
p = i;
80-
break;
81-
}
82-
}
83-
println!(
84-
"{}\x1b[0;31m{}\x1b[0m",
85-
code.get(0..p).unwrap(),
86-
code.get(p..).unwrap()
87-
);
88-
}
89-
code == expect
90-
}
63+
use crate::swc::t;
9164

9265
#[test]
93-
fn fast_refresh() {
94-
let source = r#"require("regenerator-runtime")
95-
const { mark } = require("regenerator-runtime")
66+
fn compat_fix() {
67+
let source = r#"
68+
require("regenerator-runtime")
69+
const { mark } = require("regenerator-runtime")
9670
"#;
97-
let expect = r#"(()=>window.regeneratorRuntime
71+
let expect = r#"
72+
(()=>window.regeneratorRuntime
9873
)();
9974
const { mark } = (()=>window.regeneratorRuntime
10075
)();
10176
"#;
102-
assert!(t("/app.js", source, expect));
77+
assert!(t("/app.js", source, compat_fixer_fold(), expect));
10378
}
10479
}

compiler/src/lib.rs

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,9 @@ pub struct Options {
4545
#[serde(default)]
4646
pub transpile_only: bool,
4747

48+
#[serde(default)]
49+
pub resolve_star_exports: bool,
50+
4851
#[serde(default)]
4952
pub bundle_mode: bool,
5053

@@ -99,7 +102,7 @@ pub struct TransformOutput {
99102
pub map: Option<String>,
100103
pub deps: Vec<DependencyDescriptor>,
101104
pub inline_styles: HashMap<String, InlineStyle>,
102-
pub bundle_star_exports: Option<Vec<String>>,
105+
pub star_exports: Option<Vec<String>>,
103106
}
104107

105108
#[wasm_bindgen(js_name = "parseExportNamesSync")]
@@ -153,6 +156,7 @@ pub fn transform_sync(url: &str, code: &str, options: JsValue) -> Result<JsValue
153156
source_map: options.source_map,
154157
is_dev: options.is_dev,
155158
transpile_only: options.transpile_only,
159+
resolve_star_exports: options.resolve_star_exports,
156160
},
157161
)
158162
.expect("could not transform module");
@@ -163,8 +167,8 @@ pub fn transform_sync(url: &str, code: &str, options: JsValue) -> Result<JsValue
163167
map,
164168
deps: r.dep_graph.clone(),
165169
inline_styles: r.inline_styles.clone(),
166-
bundle_star_exports: if r.bundle_star_exports.len() > 0 {
167-
Some(r.bundle_star_exports.clone())
170+
star_exports: if r.star_exports.len() > 0 {
171+
Some(r.star_exports.clone())
168172
} else {
169173
None
170174
},

compiler/src/resolve.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -53,8 +53,8 @@ pub struct Resolver {
5353
pub bundle_mode: bool,
5454
/// bundled modules
5555
pub bundle_external: IndexSet<String>,
56-
/// bundle star exports
57-
pub bundle_star_exports: Vec<String>,
56+
/// star exports
57+
pub star_exports: Vec<String>,
5858
/// extra imports
5959
pub extra_imports: IndexSet<String>,
6060
/// builtin jsx tags like `a`, `link`, `head`, etc
@@ -84,7 +84,7 @@ impl Resolver {
8484
specifier_is_remote: is_remote_url(specifier),
8585
used_builtin_jsx_tags: IndexSet::new(),
8686
dep_graph: Vec::new(),
87-
bundle_star_exports: Vec::new(),
87+
star_exports: Vec::new(),
8888
inline_styles: HashMap::new(),
8989
import_map: ImportMap::from_hashmap(import_map),
9090
aleph_pkg_uri,

compiler/src/resolve_fold.rs

Lines changed: 23 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -7,18 +7,24 @@ use swc_ecma_ast::*;
77
use swc_ecma_utils::quote_ident;
88
use swc_ecma_visit::{noop_fold_type, Fold, FoldWith};
99

10-
pub fn resolve_fold(resolver: Rc<RefCell<Resolver>>, source: Rc<SourceMap>) -> impl Fold {
10+
pub fn resolve_fold(
11+
resolver: Rc<RefCell<Resolver>>,
12+
source: Rc<SourceMap>,
13+
resolve_star_exports: bool,
14+
) -> impl Fold {
1115
ResolveFold {
1216
deno_hooks_idx: 0,
1317
resolver,
1418
source,
19+
resolve_star_exports,
1520
}
1621
}
1722

1823
pub struct ResolveFold {
1924
deno_hooks_idx: i32,
2025
resolver: Rc<RefCell<Resolver>>,
2126
source: Rc<SourceMap>,
27+
resolve_star_exports: bool,
2228
}
2329

2430
impl ResolveFold {
@@ -208,7 +214,7 @@ impl Fold for ResolveFold {
208214
let mut resolver = self.resolver.borrow_mut();
209215
let (resolved_path, fixed_url) = resolver.resolve(src.value.as_ref(), false);
210216
if resolver.bundle_mode && resolver.bundle_external.contains(fixed_url.as_str()) {
211-
resolver.bundle_star_exports.push(fixed_url.clone());
217+
resolver.star_exports.push(fixed_url.clone());
212218
ModuleItem::ModuleDecl(ModuleDecl::ExportDecl(ExportDecl {
213219
span: DUMMY_SP,
214220
decl: Decl::Var(VarDecl {
@@ -217,16 +223,25 @@ impl Fold for ResolveFold {
217223
declare: false,
218224
decls: vec![create_aleph_pack_var_decl(
219225
fixed_url.as_ref(),
220-
quote_ident!(format!("$$star_{}", resolver.bundle_star_exports.len() - 1)),
226+
quote_ident!(format!("$$star_{}", resolver.star_exports.len() - 1)),
221227
)],
222228
}),
223229
}))
224230
} else {
225-
ModuleItem::ModuleDecl(ModuleDecl::ExportAll(ExportAll {
226-
span: DUMMY_SP,
227-
src: new_str(resolved_path.into()),
228-
asserts: None,
229-
}))
231+
if self.resolve_star_exports {
232+
resolver.star_exports.push(fixed_url.clone());
233+
ModuleItem::ModuleDecl(ModuleDecl::ExportAll(ExportAll {
234+
span: DUMMY_SP,
235+
src: new_str(fixed_url.into()),
236+
asserts: None,
237+
}))
238+
} else {
239+
ModuleItem::ModuleDecl(ModuleDecl::ExportAll(ExportAll {
240+
span: DUMMY_SP,
241+
src: new_str(resolved_path.into()),
242+
asserts: None,
243+
}))
244+
}
230245
}
231246
}
232247
_ => ModuleItem::ModuleDecl(decl),

compiler/src/swc.rs

Lines changed: 35 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ use crate::resolve::Resolver;
77
use crate::resolve_fold::{resolve_fold, ExportsParser};
88
use crate::source_type::SourceType;
99

10-
use std::{cell::RefCell, path::Path, rc::Rc};
10+
use std::{cell::RefCell, cmp::min, path::Path, rc::Rc};
1111
use swc_common::{
1212
chain,
1313
comments::SingleThreadedComments,
@@ -33,6 +33,7 @@ pub struct EmitOptions {
3333
pub jsx_fragment_factory: String,
3434
pub is_dev: bool,
3535
pub transpile_only: bool,
36+
pub resolve_star_exports: bool,
3637
pub source_map: bool,
3738
}
3839

@@ -44,6 +45,7 @@ impl Default for EmitOptions {
4445
jsx_fragment_factory: "React.Fragment".into(),
4546
is_dev: false,
4647
transpile_only: false,
48+
resolve_star_exports: false,
4749
source_map: false,
4850
}
4951
}
@@ -147,7 +149,11 @@ impl SWC {
147149
let root_mark = Mark::fresh(Mark::root());
148150
let mut passes = chain!(
149151
Optional::new(
150-
resolve_fold(resolver.clone(), self.source_map.clone()),
152+
resolve_fold(
153+
resolver.clone(),
154+
self.source_map.clone(),
155+
options.resolve_star_exports,
156+
),
151157
!transpile_only
152158
),
153159
Optional::new(aleph_jsx_fold, is_jsx && !transpile_only),
@@ -298,6 +304,33 @@ fn get_syntax(source_type: &SourceType) -> Syntax {
298304
}
299305
}
300306

307+
#[allow(dead_code)]
308+
pub fn t<T: Fold>(specifier: &str, source: &str, tr: T, expect: &str) -> bool {
309+
let module = SWC::parse(specifier, source, None).expect("could not parse module");
310+
let (code, _) = swc_common::GLOBALS.set(&Globals::new(), || {
311+
module
312+
.apply_transform(tr, false)
313+
.expect("could not transpile module")
314+
});
315+
let matched = code.as_str().trim().eq(expect.trim());
316+
317+
if !matched {
318+
let mut p: usize = 0;
319+
for i in 0..min(code.len(), expect.len()) {
320+
if code.get(i..i + 1) != expect.get(i..i + 1) {
321+
p = i;
322+
break;
323+
}
324+
}
325+
println!(
326+
"{}\x1b[0;31m{}\x1b[0m",
327+
code.get(0..p).unwrap(),
328+
code.get(p..).unwrap()
329+
);
330+
}
331+
matched
332+
}
333+
301334
#[allow(dead_code)]
302335
pub fn st(specifer: &str, source: &str, bundling: bool) -> (String, Rc<RefCell<Resolver>>) {
303336
let module = SWC::parse(specifer, source, None).expect("could not parse module");

0 commit comments

Comments
 (0)