Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(es/module): Improve compatibility with cjs-module-lexer #5835

Merged
merged 6 commits into from
Sep 13, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion crates/swc/tests/fixture/interop/node/output/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,11 @@
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = exports.y = exports.x = void 0;
0 && (module.exports = {
x: _,
y: _,
default: _
});
function _export(target, all) {
for(var name in all)Object.defineProperty(target, name, {
enumerable: true,
Expand Down
142 changes: 116 additions & 26 deletions crates/swc_ecma_transforms_module/src/common_js.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ use swc_common::{
use swc_ecma_ast::*;
use swc_ecma_transforms_base::{feature::FeatureFlag, helper_expr};
use swc_ecma_utils::{
member_expr, private_ident, quote_ident, undefined, ExprFactory, FunctionFactory, IsDirective,
member_expr, private_ident, quote_ident, ExprFactory, FunctionFactory, IsDirective,
};
use swc_ecma_visit::{as_folder, noop_visit_mut_type, Fold, VisitMut, VisitMutWith};

Expand Down Expand Up @@ -254,11 +254,18 @@ where
is_export_assign: bool,
) -> impl Iterator<Item = Stmt> {
let import_interop = self.config.import_interop();
let is_node = import_interop.is_node();

let mut stmts = Vec::with_capacity(link.len());

let mut export_obj_prop_list = export.into_iter().map(Into::into).collect();

let lexer_reexport = if is_node {
self.emit_lexer_ts_reexport(&link)
} else {
None
};

link.into_iter().for_each(
|(src, LinkItem(src_span, link_specifier_set, mut link_flag))| {
// Optimize for `@swc/helpers`:
Expand All @@ -277,7 +284,7 @@ where
let is_swc_default_helper =
!link_flag.has_named() && src.starts_with("@swc/helpers/");

let is_node_default = !link_flag.has_named() && import_interop.is_node();
let is_node_default = !link_flag.has_named() && is_node;

if import_interop.is_none() || is_swc_default_helper {
link_flag -= LinkFlag::NAMESPACE;
Expand Down Expand Up @@ -371,16 +378,24 @@ where
if !export_obj_prop_list.is_empty() && !is_export_assign {
export_obj_prop_list.sort_by_key(|prop| prop.span());

if import_interop.is_node() {
export_stmts = self.emit_lexer_exports_init(&export_obj_prop_list);
}

let features = self.available_features;
let mut features = self.available_features;
let exports = self.exports();

if is_node {
if export_obj_prop_list.len() > 1 {
export_stmts.extend(self.emit_lexer_exports_init(&export_obj_prop_list));
} else {
// `cjs-module-lexer` does not support `get: ()=> foo`
// see https://github.com/nodejs/cjs-module-lexer/pull/74
features -= FeatureFlag::ArrowFunctions;
}
}

export_stmts.extend(emit_export_stmts(features, exports, export_obj_prop_list));
}

export_stmts.extend(lexer_reexport);

export_stmts.into_iter().chain(stmts)
}

Expand Down Expand Up @@ -445,29 +460,104 @@ where

/// emit [cjs-module-lexer](https://github.com/nodejs/cjs-module-lexer) friendly exports list
/// ```javascript
/// exports.foo = exports.bar = void 0;
/// 0 && (exports.foo = 0);
/// 0 && (module.exports = { foo: _, bar: _ });
/// ```
fn emit_lexer_exports_init(&mut self, export_id_list: &[ObjPropKeyIdent]) -> Vec<Stmt> {
export_id_list
.chunks(100)
.map(|group| {
let mut expr = *undefined(DUMMY_SP);

for key_value in group {
let prop = prop_name(key_value.key(), DUMMY_SP).into();

let export_binding = MemberExpr {
obj: Box::new(self.exports().into()),
span: key_value.span(),
prop,
};
fn emit_lexer_exports_init(&mut self, export_id_list: &[ObjPropKeyIdent]) -> Option<Stmt> {
match export_id_list.len() {
0 => None,
1 => {
let expr: Expr = 0.into();

let key_value = &export_id_list[0];
let prop = prop_name(key_value.key(), DUMMY_SP).into();
let export_binding = MemberExpr {
obj: Box::new(self.exports().into()),
span: key_value.span(),
prop,
};
let expr = expr.make_assign_to(op!("="), export_binding.as_pat_or_expr());
let expr = BinExpr {
span: DUMMY_SP,
op: op!("&&"),
left: 0.into(),
right: Box::new(expr),
};

expr = expr.make_assign_to(op!("="), export_binding.as_pat_or_expr());
Some(expr.into_stmt())
}
_ => {
let props = export_id_list
.iter()
.map(|key_value| prop_name(key_value.key(), DUMMY_SP))
.map(|key| KeyValueProp {
key: key.into(),
// `cjs-module-lexer` only support identifier as value
value: quote_ident!("_").into(),
})
.map(Prop::KeyValue)
.map(Box::new)
.map(PropOrSpread::Prop)
.collect();

let module_exports_assign = ObjectLit {
span: DUMMY_SP,
props,
}
.make_assign_to(
op!("="),
member_expr!(DUMMY_SP.apply_mark(self.unresolved_mark), module.exports).into(),
);

expr.into_stmt()
})
.collect()
let expr = BinExpr {
span: DUMMY_SP,
op: op!("&&"),
left: 0.into(),
right: Box::new(module_exports_assign),
};

Some(expr.into_stmt())
}
}
}

/// emit [cjs-module-lexer](https://github.com/nodejs/cjs-module-lexer) friendly exports list
/// ```javascript
/// 0 && (__export(require("foo")));
/// ```
fn emit_lexer_ts_reexport(&self, link: &Link) -> Option<Stmt> {
let mut seq_list = vec![];
link.iter().for_each(|(src, LinkItem(_, _, link_flag))| {
if link_flag.export_star() {
let import_expr =
self.resolver
.make_require_call(self.unresolved_mark, src.clone(), DUMMY_SP);

let export = Expr::Ident(quote_ident!("__export"))
.as_call(DUMMY_SP, vec![import_expr.as_arg()]);

seq_list.push(Box::new(export));
}
});

if seq_list.is_empty() {
None
} else {
let seq_expr = SeqExpr {
span: DUMMY_SP,
exprs: seq_list,
}
.into();

let expr = BinExpr {
span: DUMMY_SP,
op: op!("&&"),
left: 0.into(),
right: seq_expr,
};

Some(expr.into_stmt())
}
}

fn pure_span(&self) -> Span {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,12 @@
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
Object.defineProperty(exports, "default", {
enumerable: true,
get: ()=>_default
get () {
return _default;
}
});
0 && __export(require("react"));
const _react = _exportStar(require("react"), exports);
const _default = _react;
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,11 @@
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
Object.defineProperty(exports, "default", {
enumerable: true,
get: ()=>_default
get () {
return _default;
}
});
const _default = function() {
return "foo";
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,10 @@
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.Cachier = exports.default = void 0;
0 && (module.exports = {
default: _,
Cachier: _
});
function _export(target, all) {
for(var name in all)Object.defineProperty(target, name, {
enumerable: true,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,10 @@
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
Object.defineProperty(exports, "default", {
enumerable: true,
get: ()=>_default
get () {
return _default;
}
});
const _default = {};
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,10 @@
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
Object.defineProperty(exports, "default", {
enumerable: true,
get: ()=>_default
get () {
return _default;
}
});
const _default = [];
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,10 @@
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
Object.defineProperty(exports, "default", {
enumerable: true,
get: ()=>_default
get () {
return _default;
}
});
const _default = foo;
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,10 @@
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
Object.defineProperty(exports, "default", {
enumerable: true,
get: ()=>_default
get () {
return _default;
}
});
function _default() {}
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,11 @@
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
Object.defineProperty(exports, "default", {
enumerable: true,
get: ()=>_default
get () {
return _default;
}
});
class _default {
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,10 @@
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
Object.defineProperty(exports, "default", {
enumerable: true,
get: ()=>foo
get () {
return foo;
}
});
function foo() {}
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,11 @@
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
Object.defineProperty(exports, "default", {
enumerable: true,
get: ()=>Foo
get () {
return Foo;
}
});
class Foo {
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,10 @@
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
Object.defineProperty(exports, "default", {
enumerable: true,
get: ()=>foo
get () {
return foo;
}
});
var foo;
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,10 @@
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
Object.defineProperty(exports, "default", {
enumerable: true,
get: ()=>_default
get () {
return _default;
}
});
const _default = 42;
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,14 @@
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.f4 = exports.f3 = exports.f2 = exports.f1 = exports.y = exports.x = void 0;
0 && (module.exports = {
x: _,
y: _,
f1: _,
f2: _,
f3: _,
f4: _
});
function _export(target, all) {
for(var name in all)Object.defineProperty(target, name, {
enumerable: true,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,5 @@
Object.defineProperty(exports, "__esModule", {
value: true
});
0 && __export(require("foo"));
_exportStar(require("foo"), exports);
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,10 @@
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.foo = void 0;
Object.defineProperty(exports, "foo", {
enumerable: true,
get: ()=>_foo.foo
get () {
return _foo.foo;
}
});
const _foo = require("foo");
Loading