Skip to content

Commit

Permalink
[swc] Improve import
Browse files Browse the repository at this point in the history
  • Loading branch information
mantou132 committed Nov 26, 2024
1 parent 6de45bd commit 8af568f
Show file tree
Hide file tree
Showing 13 changed files with 85 additions and 16 deletions.
13 changes: 10 additions & 3 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ license = "Apache-2.0"
repository = "https://github.com/mantou132/gem.git"

[workspace.dependencies]
indexmap = { version = "2.6.0" }
regex = { version = "1.10.4", default-features = false }
serde = "1.0.203"
serde_json = "1.0.117"
Expand Down
1 change: 1 addition & 0 deletions crates/swc-plugin-gem/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ swc_ecma_ast = { workspace = true }
once_cell = { workspace = true }
tracing = { workspace = true }
regex = { workspace = true }
indexmap = { workspace = true, features = ["serde"] }

[dev-dependencies]
swc_ecma_parser = { workspace = true }
Expand Down
2 changes: 1 addition & 1 deletion crates/swc-plugin-gem/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "swc-plugin-gem",
"version": "0.1.1",
"version": "0.1.2",
"description": "swc plugin for Gem",
"keywords": [
"swc-plugin",
Expand Down
3 changes: 3 additions & 0 deletions crates/swc-plugin-gem/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use serde::Deserialize;
use swc_common::pass::Optional;
use swc_core::ecma::visit::VisitMutWith;
use swc_core::plugin::metadata::TransformPluginMetadataContextKind;
use swc_core::plugin::{plugin_transform, proxies::TransformPluginProgramMetadata};
use swc_ecma_ast::Program;
use visitors::import::gen_once_dts;
Expand Down Expand Up @@ -35,6 +36,8 @@ pub fn process_transform(mut program: Program, data: TransformPluginProgramMetad
let config =
serde_json::from_str::<PluginConfig>(plugin_config).expect("invalid config for gem plugin");

let _file_name = data.get_context(&TransformPluginMetadataContextKind::Filename);

// 执行在每个文件
if config.auto_import_dts {
gen_once_dts();
Expand Down
23 changes: 20 additions & 3 deletions crates/swc-plugin-gem/src/visitors/import.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
use indexmap::IndexMap;
use once_cell::sync::Lazy;
use regex::Regex;
use serde::Deserialize;
use std::{
collections::{BTreeMap, HashMap, HashSet},
collections::{HashMap, HashSet},
fs,
path::Path,
};
Expand All @@ -27,7 +28,7 @@ enum MemberOrMemberAs {
#[serde(rename_all = "camelCase")]
struct AutoImportContent {
members: HashMap<String, Vec<MemberOrMemberAs>>,
elements: HashMap<String, HashMap<String, String>>,
elements: IndexMap<String, IndexMap<String, String>>,
}

struct AutoImportConfig {
Expand Down Expand Up @@ -157,7 +158,7 @@ impl VisitMut for TransformVisitor {
node.visit_mut_children_with(self);

let mut out: Vec<ImportDecl> = vec![];
let mut available_import: HashMap<String, BTreeMap<String, String>> = HashMap::new();
let mut available_import: HashMap<String, IndexMap<String, String>> = HashMap::new();

for used_member in self.used_members.iter() {
if !self.defined_members.contains(used_member) {
Expand Down Expand Up @@ -203,6 +204,7 @@ impl VisitMut for TransformVisitor {
with: None,
phase: Default::default(),
});
break;
}
}
}
Expand Down Expand Up @@ -252,3 +254,18 @@ pub fn gen_once_dts() {
)
.expect("create dts error");
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn should_return_default_config() {
let content: &str = include_str!("../auto-import.json");
let config = serde_json::from_str::<AutoImportContent>(content).unwrap();
assert_eq!(
format!("{:?}", config.elements.get("duoyun-ui").unwrap().keys()),
r#"["dy-pat-*", "dy-input-*", "dy-*"]"#
)
}
}
13 changes: 13 additions & 0 deletions crates/swc-plugin-gem/src/visitors/memo.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,11 @@ impl TransformVisitor {
self.private_props.get(self.current_index).unwrap()
}

fn start_visit_mut_class(&mut self) {
self.private_props = Vec::new();
self.current_index = 0;
}

fn visit_mut_class(&mut self, node: &mut Box<Class>) {
for prop in self.private_props.iter() {
node.body.push(ClassMember::PrivateProp(PrivateProp {
Expand Down Expand Up @@ -54,12 +59,16 @@ impl VisitMut for TransformVisitor {
noop_visit_mut_type!();

fn visit_mut_class_decl(&mut self, node: &mut ClassDecl) {
self.start_visit_mut_class();

node.visit_mut_children_with(self);

self.visit_mut_class(&mut node.class);
}

fn visit_mut_class_expr(&mut self, node: &mut ClassExpr) {
self.start_visit_mut_class();

node.visit_mut_children_with(self);

self.visit_mut_class(&mut node.class);
Expand All @@ -80,6 +89,10 @@ impl VisitMut for TransformVisitor {
}

fn visit_mut_return_stmt(&mut self, node: &mut ReturnStmt) {
// why? 类表达式会直接走到这里来?
if self.private_props.is_empty() {
return;
}
node.arg = Some(Box::new(Expr::Assign(AssignExpr {
span: DUMMY_SP,
op: AssignOp::Assign,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ export class MyElement extends GemElement {
render() {
return html`
<dy-use></dy-use>
<dy-pat-console></dy-pat-console>
${html`<gem-link></gem-link>`}
`;
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
// @ts-nocheck
import { GemElement, html } from "@mantou/gem";
import "@mantou/gem/elements/link"
import "duoyun-ui/elements/use"
import { html, GemElement } from "@mantou/gem";
import "@mantou/gem/elements/link";
import "duoyun-ui/elements/use";
import "duoyun-ui/patterns/console";
export class MyElement extends GemElement {
render() {
return html`
<dy-use></dy-use>
<dy-pat-console></dy-pat-console>
${html`<gem-link></gem-link>`}
`;
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
// @ts-nocheck
import { adoptedStyle, attribute, css, customElement, emitter, html, styleMap, template } from "@mantou/gem";
import { css, adoptedStyle, customElement, attribute, emitter, template, styleMap, html } from "@mantou/gem";
import { render, Emitter, GemElement } from '@mantou/gem';
const style = css``;
@adoptedStyle(style)
Expand Down
15 changes: 13 additions & 2 deletions crates/swc-plugin-gem/tests/fixture/memo/input.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,19 @@
// @ts-nocheck

class MyElement {
class MyElement {}
class MyElement1 {
@memo(['src'])
get #src() {
if (bool) return '#src';
return '#src';
}
}
class MyElement2 {
get #src() {
if (bool) return '#src';
return '#src';
}
@memo(['src'])
get #src2() {
return '#src';
}
}
15 changes: 14 additions & 1 deletion crates/swc-plugin-gem/tests/fixture/memo/output.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,22 @@
// @ts-nocheck
class MyElement {
class MyElement {}
class MyElement1 {
@memo(['src'])
get #_src() {
if (bool) return this.#src = '#src';
return this.#src = '#src';
}
#src;
}
class MyElement2 {
get #src() {
if (bool) return '#src';
return '#src';
}
@memo(['src'])
get #_src2() {
return this.#src2 = '#src';
}
#src2;
}

4 changes: 2 additions & 2 deletions crates/swc-plugin-gem/tests/fixture/path/output.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
// @ts-nocheck
import '@mantou/gem/index.js';
import '@mantou/gem/helper/react-shim.js';
import "@mantou/gem.js";
import "@mantou/gem/helper/react-shim.js";

0 comments on commit 8af568f

Please sign in to comment.