Skip to content

Commit

Permalink
Handle multiple imports of next/dynamic
Browse files Browse the repository at this point in the history
  • Loading branch information
padmaia committed Aug 4, 2021
1 parent 043f1a8 commit 22b8a2d
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 6 deletions.
13 changes: 7 additions & 6 deletions packages/next/build/swc/src/next_dynamic.rs
Original file line number Diff line number Diff line change
@@ -1,23 +1,24 @@
use swc_atoms::{js_word, JsWord};
use swc_atoms::js_word;
use swc_common::{FileName, DUMMY_SP};
use swc_ecmascript::ast::{
ArrayLit, ArrowExpr, BinExpr, BinaryOp, BlockStmtOrExpr, CallExpr, Expr, ExprOrSpread,
ExprOrSuper, Ident, ImportDecl, ImportSpecifier, KeyValueProp, Lit, MemberExpr, ObjectLit, Prop,
PropName, PropOrSpread, Str, StrKind,
};
use swc_ecmascript::utils::ident::{Id, IdentLike};
use swc_ecmascript::visit::Fold;

pub fn next_dynamic(filename: FileName) -> impl Fold {
NextDynamicPatcher {
filename,
dynamic_binding: js_word!(""),
dynamic_bindings: vec![],
}
}

#[derive(Debug)]
struct NextDynamicPatcher {
filename: FileName,
dynamic_binding: JsWord,
dynamic_bindings: Vec<Id>,
}

impl Fold for NextDynamicPatcher {
Expand All @@ -30,7 +31,7 @@ impl Fold for NextDynamicPatcher {
if &src.value == "next/dynamic" {
for specifier in specifiers {
if let ImportSpecifier::Default(default_specifier) = specifier {
self.dynamic_binding = default_specifier.local.sym.clone();
self.dynamic_bindings.push(default_specifier.local.to_id());
}
}
}
Expand All @@ -40,8 +41,8 @@ impl Fold for NextDynamicPatcher {

fn fold_call_expr(&mut self, mut expr: CallExpr) -> CallExpr {
if let ExprOrSuper::Expr(i) = &expr.callee {
if let Expr::Ident(Ident { sym, .. }) = &**i {
if sym == &self.dynamic_binding {
if let Expr::Ident(identifier) = &**i {
if self.dynamic_bindings.contains(&identifier.to_id()) {
let mut import_specifier = None;
if let Expr::Arrow(ArrowExpr {
body: BlockStmtOrExpr::Expr(e),
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import dynamic1 from 'next/dynamic'
import dynamic2 from 'next/dynamic'

const DynamicComponent1 = dynamic1(() => import('../components/hello1'))
const DynamicComponent2 = dynamic2(() => import('../components/hello2'))
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import dynamic1 from 'next/dynamic'
import dynamic2 from 'next/dynamic'
const DynamicComponent1 = dynamic1(() => import('../components/hello1'), {
loadableGenerated: {
webpack: () => [require.resolveWeak('/some-project/src/some-file.js')],
modules: ['/some-project/src/some-file.js -> ' + '../components/hello1'],
},
})
const DynamicComponent2 = dynamic2(() => import('../components/hello2'), {
loadableGenerated: {
webpack: () => [require.resolveWeak('/some-project/src/some-file.js')],
modules: ['/some-project/src/some-file.js -> ' + '../components/hello2'],
},
})

0 comments on commit 22b8a2d

Please sign in to comment.