8000 support custom inser content · coder-xiaotian/swc-useclient@83510a2 · GitHub
[go: up one dir, main page]

Skip to content

Commit 83510a2

Browse files
support custom inser content
1 parent 0ac0ab9 commit 83510a2

File tree

14 files changed

+129
-27
lines changed

14 files changed

+129
-27
lines changed

Cargo.lock

Lines changed: 2 additions & 2 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

Cargo.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ lto = false
1111

1212
[dependencies]
1313
serde = "1"
14-
serde_json = "1.0.100"
14+
serde_json = "1.0.105"
1515
swc_core = { version = "0.78.*", features = ["ecma_plugin_transform", "ecma_parser"] }
1616
tracing = "0.1.37"
1717
use_client = {path = "./transform"}

README-ZH.md

Lines changed: 29 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,16 @@ pnpm i -D use-client
2020
```
2121

2222
## 配置
23-
+ include:["ui-library-path"]
23+
24+
| 属性 | 类型 | 解释 |
25+
| ---- | ---- | ---- |
26+
| include | (string \| IncludeConfig)[] | 要转换的路径数组 |
27+
28+
IncludeConfig:
29+
| 属性 | 类型 | 解释 |
30+
| ---- | ---- | ---- |
31+
| path | string | 匹配路径 |
32+
| insert | string | 自定义插入文件首行的内容,默认值:"use client" |
2433

2534
## 案例
2635
next.js配置:
@@ -55,6 +64,25 @@ swc配置:
5564
}
5665
```
5766

67+
自定义插入内容:
68+
```js
69+
const nextConfig = {
70+
experimental: {
71+
swcPlugins: [
72+
[
73+
'use-client',
74+
{
75+
include: ["path/to", {
76+
path: "path/to",
77+
insert: "use strict"
78+
}]
79+
}
80+
],
81+
]
82+
}
83+
}
84+
```
85+
5886
## 常见问题
5987

6088
+ swc 插件打断了tree shaking

README.md

Lines changed: 28 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,15 @@ pnpm i -D use-client
3030

3131
## Configuration
3232

33-
+ include:["ui-library-path"]
33+
| Property | Type | Description |
34+
| ---- | ---- | ---- |
35+
| include | (string \| IncludeConfig)[] | Array of paths to be transformed |
36+
37+
IncludeConfig:
38+
| Property | Type | Description |
39+
| ---- | ---- | ---- |
40+
| path | string | Path to match |
41+
| insert | string | Custom content to insert at the beginning of the file, default value: "use client" |
3442

3543
## Examples
3644
next.js configuration:
@@ -67,6 +75,25 @@ swc configuration:
6775
}
6876
```
6977

78+
Custom Insert Content:
79+
```js
80+
const nextConfig = {
81+
experimental: {
82+
swcPlugins: [
83+
[
84+
'use-client',
85+
{
86+
include: ["path/to", {
87+
path: "path/to",
88+
insert: "use strict"
89+
}]
90+
}
91+
],
92+
]
93+
}
94+
}
95+
```
96+
7097
## FAQ
7198

7299
+ The swc plugin interrupts tree shaking

package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "use-client",
3-
"version": "1.0.4",
3+
"version": "1.1.0",
44
"description": "A swc plugin that automatically converts component libraries into \"React Client Component\".",
55
"author": "xiaotian",
66
"license": "MIT",

src/lib.rs

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -6,25 +6,26 @@ use swc_core::{
66
},
77
};
88

9-
use use_client::{Config, TransformVisitor};
9+
use use_client::{UserConfig, TransformVisitor, normalize_config};
1010

1111
#[plugin_transform]
1212
pub fn process_transform(mut program: Program, data: TransformPluginProgramMetadata) -> Program {
13-
let config = serde_json::from_str::<Config>(
13+
let config = serde_json::from_str::<UserConfig>(
1414
&data
1515
.get_transform_plugin_config()
16-
.expect("failed to get plugin config for styled-components"),
16+
.expect("failed to get plugin config for use-client"),
1717
)
1818
.expect("invalid config for use-client");
1919
let filepath = match data.get_context(&TransformPluginMetadataContextKind::Filename) {
2020
Some(s) => s.replace("\\", "/"),
2121
None => String::from(""),
2222
};
23+
let include = normalize_config(&config);
2324

2425
program.visit_mut_with(&mut TransformVisitor {
2526
filepath: filepath,
26-
include: config.include,
27+
include,
2728
});
2829

2930
program
30-
}
31+
}

transform/src/lib.rs

Lines changed: 39 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -3,34 +3,38 @@ use swc_core::{
33
common::{BytePos, Span, SyntaxContext},
44
ecma::{
55
ast::{ExprStmt, Module, ModuleItem, Stmt, Str},
6-
visit::VisitMut,
6+
visit::{VisitMut, VisitMutWith},
77
},
88
};
99

10-
#[derive(Debug, Default, Clone, Deserialize)]
11-
#[serde(rename_all = "camelCase", deny_unknown_fields)]
12-
pub struct Config {
13-
#[serde(default)]
14-
pub include: Vec<String>,
10+
#[derive(Deserialize, Debug)]
11+
pub struct IncludeConfig {
12+
path: String,
13+
#[serde(default = "default_insert")]
14+
insert: String,
15+
}
16+
fn default_insert() -> String {
17+
String::from("use client")
1518
}
16-
1719
pub struct TransformVisitor {
1820
pub filepath: String,
19-
pub include: Vec<String>,
21+
pub include: Vec<IncludeConfig>,
2022
}
2123
impl VisitMut for TransformVisitor {
2224
fn visit_mut_module(&mut self, n: &mut Module) {
23-
println!("path: {}", self.filepath);
24-
for path in &self.include {
25-
if self.filepath.contains(path) || self.filepath.contains("/button") {
25+
for include_config in &self.include {
26+
if self.filepath.contains(include_config.path.as_str()) {
27+
let mut raw = include_config.insert.clone();
28+
raw.insert_str(0, "\"");
29+
raw.insert_str(raw.len(), "\"");
2630
let str = Str {
2731
span: Span {
2832
lo: BytePos(0),
2933
hi: BytePos(12),
3034
ctxt: SyntaxContext::from_u32(0),
3135
},
32-
value: "use client".into(),
33-
raw: Option::Some("\"use client\"".into()),
36+
value: include_config.insert.clone().into(),
37+
raw: Option::Some(raw.into()),
3438
};
3539
let e = ExprStmt {
3640
span: Span {
@@ -43,5 +47,27 @@ impl VisitMut for TransformVisitor {
4347
n.body.insert(0, ModuleItem::Stmt(Stmt::Expr(e)));
4448
}
4549
}
50+
n.visit_mut_children_with(self);
4651
}
4752
}
53+
54+
#[derive(Deserialize, Debug)]
55+
#[serde(untagged)]
56+
enum Include {
57+
Str(String),
58+
Obj(IncludeConfig),
59+
}
60+
#[derive(Deserialize, Debug)]
61+
pub struct UserConfig {
62+
include: Vec<Include>
63+
}
64+
pub fn normalize_config(config: &UserConfig) -> Vec<IncludeConfig> {
65+
let mut configs = vec![];
66+
for include in &config.include {
67+
configs.push(match include {
68+
Include::Obj(o) => IncludeConfig {path: o.path.to_string(), insert: o.insert.to_string()},
69+
Include::Str(s) => IncludeConfig {path: s.to_string(), insert: "use client".into()}
70+
})
71+
}
72+
configs
73+
}

transform/tests/fixture.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ use swc_core::{
77
},
88
};
99
use testing::fixture;
10-
use use_client::{Config< 10000 span class="pl-kos">, TransformVisitor};
10+
use use_client::{UserConfig, TransformVisitor, normalize_config};
1111

1212
fn syntax() -> Syntax {
1313
Syntax::Es(EsConfig {
@@ -21,15 +21,15 @@ fn use_client_fixture(input: PathBuf) {
2121
let dir = input.parent().unwrap();
2222
let output = dir.join("output.js");
2323
let config = read_to_string(dir.join("config.json")).expect("failed to read config.json");
24-
let config: Config = serde_json::from_str(&config).unwrap();
24+
let config: UserConfig = serde_json::from_str(&config).unwrap();
2525
let filepath: String = input.to_string_lossy().into();
2626

2727
test_fixture(
2828
syntax(),
2929
&|_tr| {
3030
as_folder(TransformVisitor {
3131
filepath: filepath.replace("\\", "/"),
32-
include: config.include.to_vec(),
32+
include: normalize_config(&config),
3333
})
3434
},
3535
&input,
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
{
2+
"include": [{"path": "fixtures/insert-custom-content", "insert": "use strict"}]
3+
}
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
function Test() {
2+
return <div>test</div>
3+
}
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
"use strict"
2+
function Test() {
3+
return <div>test</div>;
4+
}
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
{
2+
"include": [{"path": "fixtures/object-config"}]
3+
}
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
function Test() {
2+
return <div>test</div>
3+
}
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
"use client"
2+
function Test() {
3+
return <div>test</div>;
4+
}

0 commit comments

Comments
 (0)
0