Skip to content

Commit

Permalink
[swc] Support resolve path
Browse files Browse the repository at this point in the history
  • Loading branch information
mantou132 committed Nov 27, 2024
1 parent 656743b commit b7b526c
Show file tree
Hide file tree
Showing 13 changed files with 124 additions and 43 deletions.
31 changes: 31 additions & 0 deletions Cargo.lock

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

3 changes: 3 additions & 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]
node-resolve = "2.2.0"
indexmap = { version = "2.6.0" }
regex = { version = "1.10.4", default-features = false }
serde = "1.0.203"
Expand All @@ -24,3 +25,5 @@ swc_common = "4.0.0"
testing = "0.42.0"
once_cell = "1.19.0"
tracing = "0.1.40"
pathdiff = "0.2.3"
typed-path = { version = "0.9.3", default-features = false }
1 change: 1 addition & 0 deletions crates/swc-plugin-gem/.gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,4 @@
*.wasm
.swcrc
.swc
*.d.ts
3 changes: 3 additions & 0 deletions crates/swc-plugin-gem/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ crate-type = ["cdylib", "rlib"]
lto = true

[dependencies]
node-resolve = { workspace = true }
serde = { workspace = true, features = ["derive"] }
serde_json = { workspace = true }
swc_core = { workspace = true, features = ["ecma_plugin_transform"] }
Expand All @@ -22,6 +23,8 @@ once_cell = { workspace = true }
tracing = { workspace = true }
regex = { workspace = true }
indexmap = { workspace = true, features = ["serde"] }
pathdiff = { workspace = true }
typed-path = { workspace = true }

[dev-dependencies]
swc_ecma_parser = { workspace = true }
Expand Down
4 changes: 0 additions & 4 deletions crates/swc-plugin-gem/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,13 +10,9 @@
"main": "swc_plugin_gem.wasm",
"files": [],
"scripts": {
"install": "node -e \"require('@swc/core').transform('',{filename:'try-auto-import-dts'})\"",
"prepublishOnly": "cross-env CARGO_TARGET_DIR=target cargo build-wasi --release && cp target/wasm32-wasip1/release/swc_plugin_gem.wasm .",
"test": "cross-env RUST_LOG=info cargo watch -x test"
},
"devDependencies": {
"@swc/core": "^1.9.3"
},
"preferUnplugged": true,
"author": "mantou132",
"license": "ISC",
Expand Down
5 changes: 3 additions & 2 deletions crates/swc-plugin-gem/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ struct PluginConfig {
/// 在安装时会尝试读取 .swcrc 生成,有些项目没有 .swcrc 文件,需要在正式变异时生成
pub auto_import_dts: bool,
#[serde(default)]
/// 配合 import map 直接使用 esm
pub resolve_path: bool,
#[serde(default)]
pub hmr: bool,
Expand All @@ -36,7 +37,7 @@ 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);
let filename = data.get_context(&TransformPluginMetadataContextKind::Filename);

// 执行在每个文件
if config.auto_import_dts {
Expand All @@ -58,7 +59,7 @@ pub fn process_transform(mut program: Program, data: TransformPluginProgramMetad
},
Optional {
enabled: config.resolve_path,
visitor: path_transform(),
visitor: path_transform(filename.clone()),
},
));

Expand Down
53 changes: 30 additions & 23 deletions crates/swc-plugin-gem/src/visitors/import.rs
Original file line number Diff line number Diff line change
@@ -1,13 +1,12 @@
use indexmap::IndexMap;
use indexmap::{IndexMap, IndexSet};
use once_cell::sync::Lazy;
use regex::Regex;
use serde::Deserialize;
use std::{
collections::{HashMap, HashSet},
fs,
path::Path,
};
use swc_common::DUMMY_SP;
use swc_common::{SyntaxContext, DUMMY_SP};
use swc_core::ecma::visit::{noop_visit_mut_type, VisitMut, VisitMutWith};
use swc_ecma_ast::{
Callee, Class, ClassDecl, ClassExpr, Decorator, Ident, ImportDecl, ImportNamedSpecifier,
Expand Down Expand Up @@ -81,16 +80,24 @@ impl IdentString for Ident {

#[derive(Default)]
pub struct TransformVisitor {
used_members: Vec<String>,
defined_members: HashSet<String>,
used_elements: Vec<String>,
used_members: HashMap<String, SyntaxContext>,
imported_members: HashSet<String>,
used_elements: IndexSet<String>,
}

impl TransformVisitor {
fn inset_used_member(&mut self, ident: &Ident) {
let name = ident.to_name();
// 只保存顶层使用成员,会复用 SyntaxContext
if !self.used_members.contains_key(&name) {
self.used_members.insert(name, ident.ctxt);
}
}

fn visit_mut_class(&mut self, node: &Box<Class>) {
if let Some(expr) = &node.super_class {
if let Some(ident) = expr.as_ident() {
self.used_members.push(ident.to_name());
self.inset_used_member(ident);
}
}
}
Expand All @@ -100,41 +107,41 @@ impl VisitMut for TransformVisitor {
noop_visit_mut_type!();

fn visit_mut_import_specifier(&mut self, node: &mut ImportSpecifier) {
self.defined_members.insert(node.local().to_name());
self.imported_members.insert(node.local().to_name());
}

fn visit_mut_callee(&mut self, node: &mut Callee) {
if let Callee::Expr(expr) = &node {
if let Some(ident) = expr.as_ident() {
self.used_members.push(ident.to_name());
self.inset_used_member(ident);
}
}
}

fn visit_mut_jsx_element_name(&mut self, node: &mut JSXElementName) {
if let JSXElementName::Ident(ident) = node {
self.used_members.push(ident.to_name());
self.inset_used_member(ident);
}
}

fn visit_mut_decorator(&mut self, node: &mut Decorator) {
node.visit_mut_children_with(self);

if let Some(ident) = node.expr.as_ident() {
self.used_members.push(ident.to_name());
self.inset_used_member(ident);
}
}

fn visit_mut_tagged_tpl(&mut self, node: &mut TaggedTpl) {
node.visit_mut_children_with(self);

if let Some(ident) = node.tag.as_ident() {
self.used_members.push(ident.to_name());
self.inset_used_member(ident);
}

for ele in node.tpl.quasis.iter() {
for cap in CUSTOM_ELEMENT_REGEX.captures_iter(ele.raw.as_str()) {
self.used_elements.push(cap["tag"].to_string());
self.used_elements.insert(cap["tag"].to_string());
}
}
}
Expand All @@ -158,25 +165,26 @@ impl VisitMut for TransformVisitor {
node.visit_mut_children_with(self);

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

for used_member in self.used_members.iter() {
if !self.defined_members.contains(used_member) {
for (used_member, ctx) in self.used_members.iter() {
if !self.imported_members.contains(used_member) {
let pkg = GEM_AUTO_IMPORT_CONFIG.member_map.get(used_member);
if let Some(pkg) = pkg {
let set = available_import
.entry(pkg.into())
.or_insert(Default::default());
set.insert(used_member.into(), used_member.into());
set.insert(used_member.into(), (used_member.into(), ctx));
}
}
}

for (pkg, set) in available_import {
let mut specifiers: Vec<ImportSpecifier> = vec![];
for (member, _) in set {
for (member, (_, ctx)) in set {
specifiers.push(ImportSpecifier::Named(ImportNamedSpecifier {
local: member.into(),
local: Ident::new(member.into(), DUMMY_SP, ctx.clone()),
span: DUMMY_SP,
imported: None,
is_type_only: false,
Expand Down Expand Up @@ -231,19 +239,18 @@ pub fn gen_once_dts() {
}
GEN_DTS = true;
}
// https://github.com/swc-project/swc/discussions/4997
let types_dir = "/cwd/node_modules/@types/auto-import";
let mut import_list: Vec<String> = vec![];
for (member, pkg) in GEM_AUTO_IMPORT_CONFIG.member_map.iter() {
import_list.push(format!(
"const {member}: typeof import('{pkg}')['{member}'];",
));
}
fs::create_dir_all(types_dir).expect("create auto import dir error");
fs::write(
Path::new(types_dir).join("index.d.ts"),
// https://github.com/swc-project/swc/discussions/4997
"/cwd/src/auto-import.d.ts",
format!(
r#"
// AUTOMATICALLY GENERATED, DO NOT MODIFY MANUALLY.
export {{}}
declare global {{
{}
Expand Down
53 changes: 44 additions & 9 deletions crates/swc-plugin-gem/src/visitors/path.rs
Original file line number Diff line number Diff line change
@@ -1,20 +1,52 @@
///! 验证模块是否为文件,是就添加 .js 否就添加 /index.js
///! 识别模块是否为相对路径,如何是 ts 需要处理
use std::{env, path::PathBuf};

use node_resolve::Resolver;
use pathdiff::diff_paths;
use swc_core::ecma::visit::{noop_visit_mut_type, VisitMut};
use swc_ecma_ast::{CallExpr, Callee, ExprOrSpread, ImportDecl, Lit, Str};
use typed_path::{Utf8Path, Utf8UnixEncoding, Utf8WindowsEncoding};

fn resolve_path(origin: &str) -> Str {
return format!("{}.js", origin).into();
fn converting(path_buf: &PathBuf) -> String {
let windows_path = Utf8Path::<Utf8WindowsEncoding>::new(path_buf.to_str().unwrap());
windows_path.with_encoding::<Utf8UnixEncoding>().to_string()
}

#[derive(Default)]
struct TransformVisitor {}
struct TransformVisitor {
filename: Option<String>,
}

impl TransformVisitor {
fn resolve_path(&self, origin: &str) -> Str {
if let Some(filename) = &self.filename {
let cwd = env::current_dir().expect("get current dir error");
let dir = cwd.join(filename).parent().unwrap().to_path_buf();
let resolver = Resolver::new()
.with_extensions(&["ts"])
.with_basedir(dir.clone());
if let Ok(full_path) = resolver.resolve(origin) {
if let Some(relative_path) = diff_paths(&converting(&full_path), &converting(&dir))
{
if let Some(relative_path) = relative_path.to_str() {
let relative_path = relative_path.replace(".ts", ".js");
if !relative_path.starts_with(".") {
return format!("./{}", relative_path).into();
} else {
return relative_path.into();
}
}
}
}
}
origin.into()
}
}

impl VisitMut for TransformVisitor {
noop_visit_mut_type!();

fn visit_mut_import_decl(&mut self, node: &mut ImportDecl) {
node.src = resolve_path(node.src.value.as_str()).into();
node.src = self.resolve_path(node.src.value.as_str()).into();
}

// 只处理 string 的动态导入
Expand All @@ -23,13 +55,16 @@ impl VisitMut for TransformVisitor {
if let Some(Some(Lit::Str(source))) = node.args.get(0).map(|e| e.expr.as_lit()) {
node.args = vec![ExprOrSpread {
spread: None,
expr: resolve_path(source.value.as_str()).into(),
expr: self.resolve_path(source.value.as_str()).into(),
}]
}
}
}
}

pub fn path_transform() -> impl VisitMut {
TransformVisitor::default()
pub fn path_transform(filename: Option<String>) -> impl VisitMut {
TransformVisitor {
filename,
..Default::default()
}
}
6 changes: 5 additions & 1 deletion crates/swc-plugin-gem/tests/fixture.rs
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,11 @@ fn fixture_path(input: PathBuf) {

test_fixture(
get_syntax(),
&|_| visit_mut_pass(path_transform()),
&|_| {
visit_mut_pass(path_transform(Some(
"tests/fixture/path/input.ts".to_string(),
)))
},
&input,
&output,
Default::default(),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
export class MyElement extends GemElement {
render() {
return html`
<dy-use></dy-use>
<dy-use></dy-use>
<dy-pat-console></dy-pat-console>
${html`<gem-link></gem-link>`}
Expand Down
Loading

0 comments on commit b7b526c

Please sign in to comment.