Skip to content

Commit

Permalink
Add a package
Browse files Browse the repository at this point in the history
  • Loading branch information
kdy1 committed Sep 22, 2023
1 parent 854d310 commit 50b5c91
Show file tree
Hide file tree
Showing 14 changed files with 303 additions and 0 deletions.
32 changes: 32 additions & 0 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 @@ -5,6 +5,7 @@ members = [
"packages/jest",
"packages/loadable-components",
"packages/noop",
"packages/react-extra-srcmap",
"packages/react-remove-properties",
"packages/relay",
"packages/remove-console",
Expand Down
2 changes: 2 additions & 0 deletions packages/react-extra-srcmap/.npmignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
transform/
tests/
23 changes: 23 additions & 0 deletions packages/react-extra-srcmap/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
[package]
authors = ["강동윤 <[email protected]>"]
description = "SWC plugin for https://www.npmjs.com/package/babel-plugin-react-extra-srcmap"
edition = "2021"
license = "Apache-2.0"
name = "swc_plugin_react_extra_srcmap"
publish = false
version = "0.13.3"

[lib]
crate-type = ["cdylib", "rlib"]

[dependencies]
react_extra_srcmap = { path = "./transform" }
serde_json = "1.0.79"
swc_cached = "0.3.17"
swc_common = { version = "0.32.1", features = ["concurrent"] }
swc_core = { version = "0.83.5", features = ["ecma_plugin_transform"] }
swc_ecma_ast = "0.109.1"
swc_ecma_utils = "0.123.0"
swc_ecma_visit = "0.95.1"
swc_plugin_macro = "0.9.15"
tracing = { version = "0.1.37", features = ["release_max_level_off"] }
22 changes: 22 additions & 0 deletions packages/react-extra-srcmap/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
# react-extra-srcmap

See https://nextjs.org/docs/architecture/nextjs-compiler#remove-react-properties for more information.

## Config

```json
["react-extra-srcmap"]
```

or

```json
[
"react-extra-srcmap",
{
// The regexes defined here are processed in Rust so the syntax is different from
// JavaScript `RegExp`s. See https://docs.rs/regex.
"properties": ["^data-custom$"]
}
]
```
21 changes: 21 additions & 0 deletions packages/react-extra-srcmap/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
{
"name": "@swc/plugin-react-extra-srcmap",
"version": "1.5.86",
"description": "SWC plugin for https://www.npmjs.com/package/babel-plugin-react-extra-srcmap",
"main": "swc_plugin_react_extra_srcmap.wasm",
"scripts": {
"prepack": "cp ../../target/wasm32-wasi/release/swc_plugin_react_extra_srcmap.wasm ."
},
"homepage": "https://swc.rs",
"repository": {
"type": "git",
"url": "+https://github.com/swc-project/plugins.git"
},
"bugs": {
"url": "https://github.com/swc-project/plugins/issues"
},
"author": "강동윤 <[email protected]>",
"keywords": [],
"license": "Apache-2.0",
"preferUnplugged": true
}
18 changes: 18 additions & 0 deletions packages/react-extra-srcmap/src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
#![allow(clippy::not_unsafe_ptr_arg_deref)]
use swc_core::{
ecma::{ast::Program, visit::FoldWith},
plugin::{plugin_transform, proxies::TransformPluginProgramMetadata},
};

#[plugin_transform]
fn swc_plugin(program: Program, data: TransformPluginProgramMetadata) -> Program {
let config = serde_json::from_str::<Option<react_extra_srcmap::Config>>(
&data
.get_transform_plugin_config()
.expect("failed to get plugin config for react-extra-srcmap"),
)
.expect("invalid packages")
.unwrap_or_else(|| react_extra_srcmap::Config::All(true));

program.fold_with(&mut react_extra_srcmap::react_extra_srcmap(config))
}
24 changes: 24 additions & 0 deletions packages/react-extra-srcmap/transform/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
[package]
authors = ["강동윤 <[email protected]>"]
description = "AST Transforms for import modularizer"
edition = "2021"
license = "Apache-2.0"
name = "react_extra_srcmap"
repository = "https://github.com/swc-project/plugins.git"
version = "0.2.0"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
serde = { version = "1", features = ["derive"] }
swc_atoms = "0.5.9"
swc_cached = "0.3.17"
swc_common = "0.32.1"
swc_ecma_ast = "0.109.1"
swc_ecma_visit = "0.95.1"

[dev-dependencies]
swc_ecma_parser = "0.140.0"
swc_ecma_transforms_base = "0.133.2"
swc_ecma_transforms_testing = "0.136.1"
testing = "0.34.1"
70 changes: 70 additions & 0 deletions packages/react-extra-srcmap/transform/src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
use serde::Deserialize;
use swc_cached::regex::CachedRegex;
use swc_ecma_ast::*;
use swc_ecma_visit::{noop_fold_type, Fold, FoldWith};

#[derive(Clone, Debug, Deserialize)]
#[serde(untagged)]
pub enum Config {
All(bool),
WithOptions(Options),
}

impl Config {
pub fn truthy(&self) -> bool {
match self {
Config::All(b) => *b,
Config::WithOptions(_) => true,
}
}
}

#[derive(Clone, Debug, Deserialize)]
pub struct Options {
#[serde(default)]
pub properties: Vec<String>,
}

pub fn react_extra_srcmap(config: Config) -> impl Fold {
let mut properties: Vec<CachedRegex> = match config {
Config::WithOptions(x) => x
.properties
.iter()
.map(|pattern| {
CachedRegex::new(pattern).unwrap_or_else(|e| {
panic!("error compiling property regex `{}`: {}", pattern, e);
})
})
.collect(),
_ => vec![],
};
if properties.is_empty() {
// Keep the default regex identical to `babel-plugin-react-extra-srcmap`.
properties.push(CachedRegex::new(r"^data-test").unwrap());
}
RemoveProperties { properties }
}

struct RemoveProperties {
properties: Vec<CachedRegex>,
}

impl RemoveProperties {
fn should_remove_property(&self, name: &str) -> bool {
self.properties.iter().any(|p| p.is_match(name))
}
}

impl Fold for RemoveProperties {
noop_fold_type!();

fn fold_jsx_opening_element(&mut self, mut el: JSXOpeningElement) -> JSXOpeningElement {
el.attrs.retain(|attr| {
!matches!(attr, JSXAttrOrSpread::JSXAttr(JSXAttr {
name: JSXAttrName::Ident(ident),
..
}) if self.should_remove_property(ident.sym.as_ref()))
});
el.fold_children_with(self)
}
}
44 changes: 44 additions & 0 deletions packages/react-extra-srcmap/transform/tests/fixture.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
use std::path::PathBuf;

use react_extra_srcmap::Options;
use swc_common::{chain, Mark};
use swc_ecma_parser::{EsConfig, Syntax};
use swc_ecma_transforms_base::resolver;
use swc_ecma_transforms_testing::{test_fixture, FixtureTestConfig};

fn syntax() -> Syntax {
Syntax::Es(EsConfig {
jsx: true,
..Default::default()
})
}

#[testing::fixture("tests/fixture/**/input.js")]
fn fixture(input: PathBuf) {
let output = input.parent().unwrap().join("output.js");
test_fixture(
syntax(),
&|_tr| {
let unresolved_mark = Mark::new();
let top_level_mark = Mark::new();

chain!(
resolver(unresolved_mark, top_level_mark, false),
react_extra_srcmap::react_extra_srcmap(
if input.to_string_lossy().contains("custom") {
react_extra_srcmap::Config::WithOptions(Options {
properties: vec!["^data-custom$".into()],
})
} else {
react_extra_srcmap::Config::All(true)
}
)
)
},
&input,
&output,
FixtureTestConfig {
..Default::default()
},
);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
export default function Home() {
return (
<div data-test-id="1" data-custom="1a">
<div data-custom="2">
<h1 data-testid="3">Hello World!</h1>
</div>
</div>
)
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
export default function Home() {
return <div data-test-id="1">

<div>

<h1 data-testid="3">Hello World!</h1>

</div>

</div>;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
export default function Home() {
return (
<div data-test-id="1" data-custom="1a">
<div data-custom="2">
<h1 data-testid="3" nested={() => <div data-testid="4">nested</div>}>
Hello World!
</h1>
</div>
</div>
)
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
export default function Home() {
return <div data-custom="1a">

<div data-custom="2">

<h1 nested={()=><div>nested</div>}>

Hello World!

</h1>

</div>

</div>;
}

0 comments on commit 50b5c91

Please sign in to comment.