Unverified Commit 16f7084e authored by Donny/강동윤's avatar Donny/강동윤 Committed by GitHub

feat(next-swc): Update swc crates (#35996)

* Move

* Adjust

* publish = false

* Tree

* Move tests

* fixup

* Split `emotion`

* Split `styled_jsx`

* Split `styled_jsx`

* fmt

* `--fix`

* clippy

* Update crates

* fixup

* publish

* Bump

* Rename

* authors

* Update

* More update

* Oh

* Update test refs

* Update test refs

* Update again

* Fix
parent 01109734
This diff is collapsed.
...@@ -2,37 +2,35 @@ ...@@ -2,37 +2,35 @@
edition = "2018" edition = "2018"
name = "next-swc" name = "next-swc"
version = "0.0.0" version = "0.0.0"
publish = false
[lib] [lib]
crate-type = ["cdylib", "rlib"] crate-type = ["cdylib", "rlib"]
[dependencies] [dependencies]
base64 = "0.13"
byteorder = "1"
chrono = "0.4" chrono = "0.4"
easy-error = "1.0.0" easy-error = "1.0.0"
either = "1" either = "1"
fxhash = "0.2.1" fxhash = "0.2.1"
once_cell = "1.8.0" once_cell = "1.8.0"
pathdiff = "0.2.0" pathdiff = "0.2.0"
radix_fmt = "1"
regex = "1.5" regex = "1.5"
serde = "1" serde = "1"
serde_json = "1" serde_json = "1"
styled_components = "0.23.0" swc_emotion = {path="../emotion"}
swc = "0.161.1" styled_components = {path="../styled_components"}
styled_jsx = {path="../styled_jsx"}
modularize_imports = {path="../modularize_imports"}
swc = "0.164.0"
swc_atoms = "0.2.11" swc_atoms = "0.2.11"
swc_common = { version = "0.17.18", features = ["concurrent", "sourcemap"] } swc_common = { version = "0.17.19", features = ["concurrent", "sourcemap"] }
swc_css = "0.103.0"
swc_ecma_loader = { version = "0.29.0", features = ["node", "lru"] } swc_ecma_loader = { version = "0.29.0", features = ["node", "lru"] }
swc_ecmascript = { version = "0.140.0", features = ["codegen", "minifier", "optimization", "parser", "react", "transforms", "typescript", "utils", "visit"] } swc_ecmascript = { version = "0.143.0", features = ["codegen", "minifier", "optimization", "parser", "react", "transforms", "typescript", "utils", "visit"] }
swc_node_base = "0.5.1"
swc_cached = "0.1.1" swc_cached = "0.1.1"
swc_css_prefixer = "0.99.3" tracing = { version = "0.1.32", features = ["release_max_level_off"] }
tracing = {version = "0.1.28", features = ["release_max_level_off"]}
handlebars = "4.2.1"
[dev-dependencies] [dev-dependencies]
swc_ecma_transforms_testing = "0.75.0" swc_ecma_transforms_testing = "0.77.0"
testing = "0.19.1" testing = "0.19.1"
walkdir = "2.3.2" walkdir = "2.3.2"
...@@ -104,6 +104,7 @@ fn get_object_pattern(array_pattern: &ArrayPat) -> Pat { ...@@ -104,6 +104,7 @@ fn get_object_pattern(array_pattern: &ArrayPat) -> Pat {
key: PropName::Num(Number { key: PropName::Num(Number {
value: i as f64, value: i as f64,
span: DUMMY_SP, span: DUMMY_SP,
raw: None,
}), }),
value: Box::new(elem.clone()), value: Box::new(elem.clone()),
}) })
......
...@@ -48,9 +48,7 @@ use swc_ecmascript::visit::Fold; ...@@ -48,9 +48,7 @@ use swc_ecmascript::visit::Fold;
pub mod amp_attributes; pub mod amp_attributes;
mod auto_cjs; mod auto_cjs;
pub mod disallow_re_export_all_in_page; pub mod disallow_re_export_all_in_page;
pub mod emotion;
pub mod hook_optimizer; pub mod hook_optimizer;
pub mod modularize_imports;
pub mod next_dynamic; pub mod next_dynamic;
pub mod next_ssg; pub mod next_ssg;
pub mod page_config; pub mod page_config;
...@@ -59,7 +57,6 @@ pub mod react_remove_properties; ...@@ -59,7 +57,6 @@ pub mod react_remove_properties;
pub mod relay; pub mod relay;
pub mod remove_console; pub mod remove_console;
pub mod shake_exports; pub mod shake_exports;
pub mod styled_jsx;
mod top_level_binding_collector; mod top_level_binding_collector;
#[derive(Clone, Debug, Deserialize)] #[derive(Clone, Debug, Deserialize)]
...@@ -103,7 +100,7 @@ pub struct TransformOptions { ...@@ -103,7 +100,7 @@ pub struct TransformOptions {
pub shake_exports: Option<shake_exports::Config>, pub shake_exports: Option<shake_exports::Config>,
#[serde(default)] #[serde(default)]
pub emotion: Option<emotion::EmotionOptions>, pub emotion: Option<swc_emotion::EmotionOptions>,
#[serde(default)] #[serde(default)]
pub modularize_imports: Option<modularize_imports::Config>, pub modularize_imports: Option<modularize_imports::Config>,
...@@ -188,7 +185,7 @@ pub fn custom_before_pass<'a, C: Comments + 'a>( ...@@ -188,7 +185,7 @@ pub fn custom_before_pass<'a, C: Comments + 'a>(
} }
if let FileName::Real(path) = &file.name { if let FileName::Real(path) = &file.name {
path.to_str().map(|_| { path.to_str().map(|_| {
Either::Left(emotion::EmotionTransformer::new( Either::Left(swc_emotion::EmotionTransformer::new(
config.clone(), config.clone(),
path, path,
cm, cm,
......
use next_swc::{ use next_swc::{
disallow_re_export_all_in_page::disallow_re_export_all_in_page, next_dynamic::next_dynamic, disallow_re_export_all_in_page::disallow_re_export_all_in_page, next_dynamic::next_dynamic,
next_ssg::next_ssg, styled_jsx::styled_jsx, next_ssg::next_ssg,
}; };
use std::path::PathBuf; use std::path::PathBuf;
use swc_common::FileName; use swc_common::FileName;
...@@ -44,22 +44,6 @@ fn next_dynamic_errors(input: PathBuf) { ...@@ -44,22 +44,6 @@ fn next_dynamic_errors(input: PathBuf) {
); );
} }
#[fixture("tests/errors/styled-jsx/**/input.js")]
fn styled_jsx_errors(input: PathBuf) {
let output = input.parent().unwrap().join("output.js");
let file_name = match input.to_str().unwrap().contains("ts-with-css-resolve") {
true => FileName::Real(PathBuf::from("/some-project/src/some-file.ts")),
false => FileName::Real(PathBuf::from("/some-project/src/some-file.js")),
};
test_fixture_allowing_error(
syntax(),
&|t| styled_jsx(t.cm.clone(), file_name.clone()),
&input,
&output,
);
}
#[fixture("tests/errors/next-ssg/**/input.js")] #[fixture("tests/errors/next-ssg/**/input.js")]
fn next_ssg_errors(input: PathBuf) { fn next_ssg_errors(input: PathBuf) {
let output = input.parent().unwrap().join("output.js"); let output = input.parent().unwrap().join("output.js");
......
use next_swc::{ use next_swc::{
amp_attributes::amp_attributes, amp_attributes::amp_attributes,
emotion::{self, EmotionOptions},
modularize_imports::modularize_imports,
next_dynamic::next_dynamic, next_dynamic::next_dynamic,
next_ssg::next_ssg, next_ssg::next_ssg,
page_config::page_config_test, page_config::page_config_test,
...@@ -9,17 +7,13 @@ use next_swc::{ ...@@ -9,17 +7,13 @@ use next_swc::{
relay::{relay, Config as RelayConfig, RelayLanguageConfig}, relay::{relay, Config as RelayConfig, RelayLanguageConfig},
remove_console::remove_console, remove_console::remove_console,
shake_exports::{shake_exports, Config as ShakeExportsConfig}, shake_exports::{shake_exports, Config as ShakeExportsConfig},
styled_jsx::styled_jsx,
}; };
use std::path::PathBuf; use std::path::PathBuf;
use swc_common::{chain, comments::SingleThreadedComments, FileName, Mark, Span, DUMMY_SP}; use swc_common::{chain, comments::SingleThreadedComments, FileName, Mark};
use swc_ecma_transforms_testing::{test, test_fixture}; use swc_ecma_transforms_testing::{test, test_fixture};
use swc_ecmascript::{ use swc_ecmascript::{
parser::{EsConfig, Syntax, TsConfig}, parser::{EsConfig, Syntax},
transforms::{ transforms::react::jsx,
react::{jsx, Runtime},
resolver,
},
}; };
use testing::fixture; use testing::fixture;
...@@ -30,13 +24,6 @@ fn syntax() -> Syntax { ...@@ -30,13 +24,6 @@ fn syntax() -> Syntax {
}) })
} }
fn ts_syntax() -> Syntax {
Syntax::Typescript(TsConfig {
tsx: true,
..Default::default()
})
}
#[fixture("tests/fixture/amp/**/input.js")] #[fixture("tests/fixture/amp/**/input.js")]
fn amp_attributes_fixture(input: PathBuf) { fn amp_attributes_fixture(input: PathBuf) {
let output = input.parent().unwrap().join("output.js"); let output = input.parent().unwrap().join("output.js");
...@@ -120,56 +107,6 @@ fn next_ssg_fixture(input: PathBuf) { ...@@ -120,56 +107,6 @@ fn next_ssg_fixture(input: PathBuf) {
); );
} }
#[fixture("tests/fixture/styled-jsx/**/input.js")]
fn styled_jsx_fixture(input: PathBuf) {
let output = input.parent().unwrap().join("output.js");
test_fixture(
syntax(),
&|t| {
chain!(
resolver(),
styled_jsx(
t.cm.clone(),
FileName::Real(PathBuf::from("/some-project/src/some-file.js"))
)
)
},
&input,
&output,
);
test_fixture(
syntax(),
&|t| {
// `resolver` uses `Mark` which is stored in a thread-local storage (namely
// swc_common::GLOBALS), and this loop will make `Mark` to be different from the
// invocation above.
//
// 1000 is used because in future I (kdy1) may optimize logic of resolver.
for _ in 0..1000 {
let _mark = Mark::fresh(Mark::root());
}
chain!(
resolver(),
styled_jsx(
t.cm.clone(),
FileName::Real(PathBuf::from("/some-project/src/some-file.js"))
)
)
},
&input,
&output,
);
}
pub struct DropSpan;
impl swc_ecmascript::visit::VisitMut for DropSpan {
fn visit_mut_span(&mut self, span: &mut Span) {
*span = DUMMY_SP
}
}
#[fixture("tests/fixture/page-config/**/input.js")] #[fixture("tests/fixture/page-config/**/input.js")]
fn page_config_fixture(input: PathBuf) { fn page_config_fixture(input: PathBuf) {
let output = input.parent().unwrap().join("output.js"); let output = input.parent().unwrap().join("output.js");
...@@ -272,87 +209,3 @@ fn shake_exports_fixture_default(input: PathBuf) { ...@@ -272,87 +209,3 @@ fn shake_exports_fixture_default(input: PathBuf) {
&output, &output,
); );
} }
#[fixture("tests/fixture/emotion/*/input.tsx")]
fn next_emotion_fixture(input: PathBuf) {
let output = input.parent().unwrap().join("output.ts");
test_fixture(
ts_syntax(),
&|tr| {
let top_level_mark = Mark::fresh(Mark::root());
let jsx = jsx::<SingleThreadedComments>(
tr.cm.clone(),
Some(tr.comments.as_ref().clone()),
swc_ecmascript::transforms::react::Options {
next: false,
runtime: Some(Runtime::Automatic),
throw_if_namespace: false,
development: false,
use_builtins: true,
use_spread: true,
..Default::default()
},
top_level_mark,
);
chain!(
emotion::emotion(
EmotionOptions {
enabled: Some(true),
sourcemap: Some(true),
auto_label: Some(true),
..Default::default()
},
&PathBuf::from("input.ts"),
tr.cm.clone(),
tr.comments.as_ref().clone(),
),
jsx
)
},
&input,
&output,
);
}
#[fixture("tests/fixture/modularize-imports/**/input.js")]
fn modularize_imports_fixture(input: PathBuf) {
use next_swc::modularize_imports::PackageConfig;
let output = input.parent().unwrap().join("output.js");
test_fixture(
syntax(),
&|_tr| {
modularize_imports(next_swc::modularize_imports::Config {
packages: vec![
(
"react-bootstrap".to_string(),
PackageConfig {
transform: "react-bootstrap/lib/{{member}}".into(),
prevent_full_import: false,
skip_default_conversion: false,
},
),
(
"my-library/?(((\\w*)?/?)*)".to_string(),
PackageConfig {
transform: "my-library/{{ matches.[1] }}/{{member}}".into(),
prevent_full_import: false,
skip_default_conversion: false,
},
),
(
"my-library-2".to_string(),
PackageConfig {
transform: "my-library-2/{{ camelCase member }}".into(),
prevent_full_import: false,
skip_default_conversion: true,
},
),
]
.into_iter()
.collect(),
})
},
&input,
&output,
);
}
...@@ -31,7 +31,7 @@ fn test(input: &Path, minify: bool) { ...@@ -31,7 +31,7 @@ fn test(input: &Path, minify: bool) {
swc: swc::config::Options { swc: swc::config::Options {
swcrc: true, swcrc: true,
is_module: swc::config::IsModule::Bool(true), is_module: swc::config::IsModule::Bool(true),
output_path: Some(output.to_path_buf()), output_path: Some(output.clone()),
config: swc::config::Config { config: swc::config::Config {
jsc: swc::config::JscConfig { jsc: swc::config::JscConfig {
......
[package]
authors = ["강동윤 <kdy1997.dev@gmail.com>"]
edition = "2018"
description = "AST Transforms for emotion"
license = "Apache-2.0"
name = "swc_emotion"
repository = "https://github.com/vercel/next.js.git"
version = "0.2.1"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
base64 = "0.13"
byteorder = "1"
fxhash = "0.2.1"
once_cell = "1.8.0"
radix_fmt = "1"
regex = "1.5"
serde = "1"
sourcemap = "6.0.1"
swc_atoms = "0.2.11"
swc_common = { version = "0.17.19", features = ["concurrent", "sourcemap"] }
swc_ecmascript = { version = "0.143.0", features = ["codegen", "utils", "visit"] }
[dev-dependencies]
swc_ecma_transforms_testing = "0.77.0"
testing = "0.19.1"
...@@ -46,8 +46,8 @@ mod test { ...@@ -46,8 +46,8 @@ mod test {
let s2 = "abcdeg"; let s2 = "abcdeg";
for i in 0..5 { for i in 0..5 {
assert_eq!( assert_eq!(
murmurhash2(&s1[i..5].as_bytes(), 0), murmurhash2(s1[i..5].as_bytes(), 0),
murmurhash2(&s2[i..5].as_bytes(), 0) murmurhash2(s2[i..5].as_bytes(), 0)
); );
} }
} }
......
...@@ -6,14 +6,14 @@ use fxhash::FxHashMap; ...@@ -6,14 +6,14 @@ use fxhash::FxHashMap;
use once_cell::sync::Lazy; use once_cell::sync::Lazy;
use regex::Regex; use regex::Regex;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use swc::sourcemap::{RawToken, SourceMap as RawSourcemap}; use sourcemap::{RawToken, SourceMap as RawSourcemap};
use swc_atoms::JsWord; use swc_atoms::JsWord;
use swc_common::comments::Comments; use swc_common::comments::Comments;
use swc_common::util::take::Take; use swc_common::util::take::Take;
use swc_common::{BytePos, SourceMap, DUMMY_SP}; use swc_common::{BytePos, SourceMap, DUMMY_SP};
use swc_ecmascript::ast::{ use swc_ecmascript::ast::{
ArrayLit, JSXAttr, JSXAttrName, JSXAttrOrSpread, JSXAttrValue, JSXElementName, JSXExpr, ArrayLit, CallExpr, JSXAttr, JSXAttrName, JSXAttrOrSpread, JSXAttrValue, JSXElementName,
JSXExprContainer, JSXObject, JSXExpr, JSXExprContainer, JSXObject,
}; };
use swc_ecmascript::utils::ident::IdentLike; use swc_ecmascript::utils::ident::IdentLike;
use swc_ecmascript::utils::{ExprFactory, Id}; use swc_ecmascript::utils::{ExprFactory, Id};
...@@ -23,7 +23,7 @@ use swc_ecmascript::{ ...@@ -23,7 +23,7 @@ use swc_ecmascript::{
MemberProp, ObjectLit, Pat, Prop, PropName, PropOrSpread, Tpl, VarDeclarator, MemberProp, ObjectLit, Pat, Prop, PropName, PropOrSpread, Tpl, VarDeclarator,
}, },
codegen::util::SourceMapperExt, codegen::util::SourceMapperExt,
visit::{swc_ecma_ast::CallExpr, Fold, FoldWith}, visit::{Fold, FoldWith},
}; };
mod hash; mod hash;
......
use std::path::PathBuf;
use swc_common::{chain, comments::SingleThreadedComments, Mark};
use swc_ecma_transforms_testing::test_fixture;
use swc_ecmascript::{
parser::{Syntax, TsConfig},
transforms::react::{jsx, Runtime},
};
use swc_emotion::EmotionOptions;
use testing::fixture;
fn ts_syntax() -> Syntax {
Syntax::Typescript(TsConfig {
tsx: true,
..Default::default()
})
}
#[fixture("tests/fixture/*/input.tsx")]
fn next_emotion_fixture(input: PathBuf) {
let output = input.parent().unwrap().join("output.ts");
test_fixture(
ts_syntax(),
&|tr| {
let top_level_mark = Mark::fresh(Mark::root());
let jsx = jsx::<SingleThreadedComments>(
tr.cm.clone(),
Some(tr.comments.as_ref().clone()),
swc_ecmascript::transforms::react::Options {
next: false,
runtime: Some(Runtime::Automatic),
throw_if_namespace: false,
development: false,
use_builtins: true,
use_spread: true,
..Default::default()
},
top_level_mark,
);
chain!(
swc_emotion::emotion(
EmotionOptions {
enabled: Some(true),
sourcemap: Some(true),
auto_label: Some(true),
..Default::default()
},
&PathBuf::from("input.ts"),
tr.cm.clone(),
tr.comments.as_ref().clone(),
),
jsx
)
},
&input,
&output,
);
}
[package]
authors = ["강동윤 <kdy1997.dev@gmail.com>"]
description = "AST Transforms for import modularizer"
edition = "2018"
license = "Apache-2.0"
name = "modularize_imports"
repository = "https://github.com/vercel/next.js.git"
version = "0.1.1"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
handlebars = "4.2.1"
once_cell = "1.8.0"
regex = "1.5"
serde = "1"
swc_cached = "0.1.1"
swc_ecmascript = {version = "0.143.0", features = ["visit"]}
[dev-dependencies]
swc_ecma_transforms_testing = "0.77.0"
testing = "0.19.1"
use std::path::PathBuf;
use modularize_imports::{modularize_imports, PackageConfig};
use swc_ecma_transforms_testing::test_fixture;
use swc_ecmascript::parser::{EsConfig, Syntax};
use testing::fixture;
fn syntax() -> Syntax {
Syntax::Es(EsConfig {
jsx: true,
..Default::default()
})
}
#[fixture("tests/fixture/**/input.js")]
fn modularize_imports_fixture(input: PathBuf) {
let output = input.parent().unwrap().join("output.js");
test_fixture(
syntax(),
&|_tr| {
modularize_imports(modularize_imports::Config {
packages: vec![
(
"react-bootstrap".to_string(),
PackageConfig {
transform: "react-bootstrap/lib/{{member}}".into(),
prevent_full_import: false,
skip_default_conversion: false,
},
),
(
"my-library/?(((\\w*)?/?)*)".to_string(),
PackageConfig {
transform: "my-library/{{ matches.[1] }}/{{member}}".into(),
prevent_full_import: false,
skip_default_conversion: false,
},
),
(
"my-library-2".to_string(),
PackageConfig {
transform: "my-library-2/{{ camelCase member }}".into(),
prevent_full_import: false,
skip_default_conversion: true,
},
),
]
.into_iter()
.collect(),
})
},
&input,
&output,
);
}
...@@ -2,6 +2,7 @@ ...@@ -2,6 +2,7 @@
edition = "2018" edition = "2018"
name = "next-swc-napi" name = "next-swc-napi"
version = "0.0.0" version = "0.0.0"
publish = false
[lib] [lib]
crate-type = ["cdylib", "rlib"] crate-type = ["cdylib", "rlib"]
...@@ -16,13 +17,13 @@ next-swc = {version = "0.0.0", path = "../core"} ...@@ -16,13 +17,13 @@ next-swc = {version = "0.0.0", path = "../core"}
once_cell = "1.8.0" once_cell = "1.8.0"
serde = "1" serde = "1"
serde_json = "1" serde_json = "1"
swc = "0.161.1" swc = "0.164.0"
swc_atoms = "0.2.11" swc_atoms = "0.2.11"
swc_bundler = { version = "0.130.0", features = ["concurrent"] } swc_bundler = { version = "0.133.0", features = ["concurrent"] }
swc_common = { version = "0.17.18", features = ["concurrent", "sourcemap"] } swc_common = { version = "0.17.19", features = ["concurrent", "sourcemap"] }
swc_ecma_loader = { version = "0.29.0", features = ["node", "lru"] } swc_ecma_loader = { version = "0.29.0", features = ["node", "lru"] }
swc_ecmascript = { version = "0.140.0", features = ["codegen", "minifier", "optimization", "parser", "react", "transforms", "typescript", "utils", "visit"] } swc_ecmascript = { version = "0.143.0", features = ["codegen", "minifier", "optimization", "parser", "react", "transforms", "typescript", "utils", "visit"] }
swc_node_base = "0.5.1" swc_node_base = "0.5.2"
[build-dependencies] [build-dependencies]
napi-build = "1" napi-build = "1"
...@@ -251,7 +251,7 @@ pub fn transform_sync(cx: CallContext) -> napi::Result<JsObject> { ...@@ -251,7 +251,7 @@ pub fn transform_sync(cx: CallContext) -> napi::Result<JsObject> {
fn test_deser() { fn test_deser() {
const JSON_STR: &str = r#"{"jsc":{"parser":{"syntax":"ecmascript","dynamicImport":true,"jsx":true},"transform":{"react":{"runtime":"automatic","pragma":"React.createElement","pragmaFrag":"React.Fragment","throwIfNamespace":true,"development":false,"useBuiltins":true}},"target":"es5"},"filename":"/Users/timneutkens/projects/next.js/packages/next/dist/client/next.js","sourceMaps":false,"sourceFileName":"/Users/timneutkens/projects/next.js/packages/next/dist/client/next.js"}"#; const JSON_STR: &str = r#"{"jsc":{"parser":{"syntax":"ecmascript","dynamicImport":true,"jsx":true},"transform":{"react":{"runtime":"automatic","pragma":"React.createElement","pragmaFrag":"React.Fragment","throwIfNamespace":true,"development":false,"useBuiltins":true}},"target":"es5"},"filename":"/Users/timneutkens/projects/next.js/packages/next/dist/client/next.js","sourceMaps":false,"sourceFileName":"/Users/timneutkens/projects/next.js/packages/next/dist/client/next.js"}"#;
let tr: TransformOptions = serde_json::from_str(&JSON_STR).unwrap(); let tr: TransformOptions = serde_json::from_str(JSON_STR).unwrap();
println!("{:#?}", tr); println!("{:#?}", tr);
} }
...@@ -260,7 +260,7 @@ fn test_deser() { ...@@ -260,7 +260,7 @@ fn test_deser() {
fn test_deserialize_transform_regenerator() { fn test_deserialize_transform_regenerator() {
const JSON_STR: &str = r#"{"jsc":{"parser":{"syntax":"ecmascript","dynamicImport":true,"jsx":true},"transform":{ "regenerator": { "importPath": "foo" }, "react":{"runtime":"automatic","pragma":"React.createElement","pragmaFrag":"React.Fragment","throwIfNamespace":true,"development":false,"useBuiltins":true}},"target":"es5"},"filename":"/Users/timneutkens/projects/next.js/packages/next/dist/client/next.js","sourceMaps":false,"sourceFileName":"/Users/timneutkens/projects/next.js/packages/next/dist/client/next.js"}"#; const JSON_STR: &str = r#"{"jsc":{"parser":{"syntax":"ecmascript","dynamicImport":true,"jsx":true},"transform":{ "regenerator": { "importPath": "foo" }, "react":{"runtime":"automatic","pragma":"React.createElement","pragmaFrag":"React.Fragment","throwIfNamespace":true,"development":false,"useBuiltins":true}},"target":"es5"},"filename":"/Users/timneutkens/projects/next.js/packages/next/dist/client/next.js","sourceMaps":false,"sourceFileName":"/Users/timneutkens/projects/next.js/packages/next/dist/client/next.js"}"#;
let tr: TransformOptions = serde_json::from_str(&JSON_STR).unwrap(); let tr: TransformOptions = serde_json::from_str(JSON_STR).unwrap();
println!("{:#?}", tr); println!("{:#?}", tr);
} }
[package]
authors = ["강동윤 <kdy1997.dev@gmail.com>"]
description = "AST Transforms for styled-components"
edition = "2018"
license = "Apache-2.0"
name = "styled_components"
repository = "https://github.com/vercel/next.js.git"
version = "0.26.0"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
Inflector = "0.11.4"
once_cell = "1.10.0"
regex = {version = "1.5.4", features = ["std", "perf"], default-features = false}
serde = {version = "1.0.130", features = ["derive"]}
swc_atoms = "0.2.11"
swc_common = { version = "0.17.19", features = ["concurrent"] }
swc_ecmascript = { version = "0.143.0", features = ["utils", "visit"] }
tracing = "0.1.32"
[dev-dependencies]
serde_json = "1"
swc_ecma_transforms_testing = "0.77.0"
swc_ecmascript = { version = "0.143.0", features = ["parser", "transforms"] }
testing = "0.19.1"
pub use crate::{
utils::{analyze, analyzer, State},
visitors::{
display_name_and_id::display_name_and_id, transpile_css_prop::transpile::transpile_css_prop,
},
};
use serde::Deserialize;
use std::{cell::RefCell, rc::Rc, sync::Arc};
use swc_atoms::JsWord;
use swc_common::{chain, SourceFile};
use swc_ecmascript::visit::{Fold, VisitMut};
mod css;
mod utils;
mod visitors;
#[derive(Debug, Default, Clone, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct Config {
#[serde(default = "true_by_default")]
pub display_name: bool,
#[serde(default = "true_by_default")]
pub ssr: bool,
#[serde(default = "true_by_default")]
pub file_name: bool,
#[serde(default)]
pub namespace: String,
#[serde(default)]
pub top_level_import_paths: Vec<JsWord>,
#[serde(default)]
pub transpile_template_literals: bool,
#[serde(default)]
pub minify: bool,
#[serde(default)]
pub css_prop: bool,
}
fn true_by_default() -> bool {
true
}
impl Config {
pub(crate) fn use_namespace(&self) -> String {
if self.namespace.is_empty() {
return String::new();
}
format!("{}__", self.namespace)
}
}
/// NOTE: **This is not complete**.
///
/// Only [analyzer] and [display_name_and_id] is implemented.
pub fn styled_components(file: Arc<SourceFile>, config: Config) -> impl Fold + VisitMut {
let state: Rc<RefCell<State>> = Default::default();
let config = Rc::new(config);
chain!(
analyzer(config.clone(), state.clone()),
display_name_and_id(file, config, state),
transpile_css_prop()
)
}
use super::State;
use crate::Config;
use std::{cell::RefCell, rc::Rc};
use swc_ecmascript::{
ast::*,
utils::{ident::IdentLike, ExprExt},
visit::{as_folder, noop_visit_mut_type, noop_visit_type, Fold, Visit, VisitMut, VisitWith},
};
pub fn analyzer(config: Rc<Config>, state: Rc<RefCell<State>>) -> impl VisitMut + Fold {
as_folder(AsAnalyzer { config, state })
}
struct AsAnalyzer {
config: Rc<Config>,
state: Rc<RefCell<State>>,
}
impl VisitMut for AsAnalyzer {
noop_visit_mut_type!();
fn visit_mut_module(&mut self, p: &mut Module) {
let mut v = Analyzer {
config: &self.config,
state: &mut *self.state.borrow_mut(),
};
p.visit_with(&mut v);
}
fn visit_mut_script(&mut self, p: &mut Script) {
let mut v = Analyzer {
config: &self.config,
state: &mut *self.state.borrow_mut(),
};
p.visit_with(&mut v);
}
}
pub fn analyze(config: &Config, program: &Program) -> State {
let mut state = State::default();
let mut v = Analyzer {
config,
state: &mut state,
};
program.visit_with(&mut v);
state
}
struct Analyzer<'a> {
config: &'a Config,
state: &'a mut State,
}
impl Visit for Analyzer<'_> {
noop_visit_type!();
fn visit_var_declarator(&mut self, v: &VarDeclarator) {
v.visit_children_with(self);
if let Pat::Ident(name) = &v.name {
if let Some(Expr::Call(CallExpr {
callee: Callee::Expr(callee),
args,
..
})) = v.init.as_deref()
{
if callee.is_ident_ref_to("require".into())
&& args.len() == 1
&& args[0].spread.is_none()
{
if let Expr::Lit(Lit::Str(v)) = &*args[0].expr {
let is_styled = if self.config.top_level_import_paths.is_empty() {
&*v.value == "styled-components"
|| v.value.starts_with("styled-components/")
} else {
self.config.top_level_import_paths.contains(&v.value)
};
if is_styled {
self.state.styled_required = Some(name.id.to_id());
}
}
}
}
}
}
fn visit_import_decl(&mut self, i: &ImportDecl) {
let is_custom = !self.config.top_level_import_paths.is_empty();
let is_styled = if self.config.top_level_import_paths.is_empty() {
&*i.src.value == "styled-components" || i.src.value.starts_with("styled-components/")
} else {
self.config.top_level_import_paths.contains(&i.src.value)
};
if is_styled {
for s in &i.specifiers {
match s {
ImportSpecifier::Named(s) => {
if is_custom
&& s.imported
.as_ref()
.map(|v| match v {
ModuleExportName::Ident(v) => &*v.sym,
ModuleExportName::Str(v) => &*v.value,
})
.unwrap_or(&*s.local.sym)
== "styled"
{
self.state.imported_local_name = Some(s.local.to_id());
}
}
ImportSpecifier::Default(s) => {
self.state.imported_local_name = Some(s.local.to_id());
}
ImportSpecifier::Namespace(s) => {
self.state.imported_local_ns = Some(s.local.to_id());
}
}
}
}
}
}
This diff is collapsed.
pub mod assign_style_required;
pub mod display_name_and_id;
pub mod minify;
pub mod transpile_css_prop;
use swc_common::collections::AHashSet;
use swc_ecmascript::{
ast::{
ArrowExpr, ClassDecl, FnDecl, Function, ImportDefaultSpecifier, ImportNamedSpecifier,
ImportStarAsSpecifier, ObjectPatProp, Pat, VarDeclarator,
},
utils::{ident::IdentLike, Id},
visit::{noop_visit_type, Visit, VisitWith},
};
// Modified from swc_ecma_utils/src/lib.rs:BindingCollector.
pub struct TopLevelBindingCollector {
bindings: AHashSet<Id>,
in_pat_decl: bool,
}
impl TopLevelBindingCollector {
fn add(&mut self, i: &Id) {
self.bindings.insert(i.clone());
}
}
impl Visit for TopLevelBindingCollector {
noop_visit_type!();
fn visit_class_decl(&mut self, node: &ClassDecl) {
self.add(&node.ident.to_id());
}
fn visit_fn_decl(&mut self, node: &FnDecl) {
self.add(&node.ident.to_id());
}
fn visit_pat(&mut self, node: &Pat) {
if !self.in_pat_decl {
return;
}
match node {
Pat::Ident(i) => self.add(&i.id.to_id()),
Pat::Object(o) => {
for prop in o.props.iter() {
match prop {
ObjectPatProp::Assign(a) => self.add(&a.key.to_id()),
ObjectPatProp::KeyValue(k) => k.value.visit_with(self),
ObjectPatProp::Rest(_) => {}
}
}
}
Pat::Array(a) => {
for elem in a.elems.iter() {
elem.visit_with(self);
}
}
Pat::Assign(a) => {
a.left.visit_with(self);
}
_ => {}
}
}
fn visit_arrow_expr(&mut self, _: &ArrowExpr) {}
fn visit_function(&mut self, _: &Function) {}
fn visit_import_default_specifier(&mut self, node: &ImportDefaultSpecifier) {
self.add(&node.local.to_id());
}
fn visit_import_named_specifier(&mut self, node: &ImportNamedSpecifier) {
self.add(&node.local.to_id());
}
fn visit_import_star_as_specifier(&mut self, node: &ImportStarAsSpecifier) {
self.add(&node.local.to_id());
}
fn visit_var_declarator(&mut self, node: &VarDeclarator) {
let old = self.in_pat_decl;
self.in_pat_decl = true;
node.name.visit_with(self);
self.in_pat_decl = old;
}
}
pub fn collect_top_level_decls<N>(n: &N) -> AHashSet<Id>
where
N: VisitWith<TopLevelBindingCollector>,
{
let mut v = TopLevelBindingCollector {
bindings: Default::default(),
in_pat_decl: false,
};
n.visit_with(&mut v);
v.bindings
}
#![deny(unused)]
use std::{fs::read_to_string, path::PathBuf};
use styled_components::{styled_components, Config};
use swc_common::chain;
use swc_ecma_transforms_testing::test_fixture;
use swc_ecmascript::{
parser::{EsConfig, Syntax},
transforms::resolver,
};
#[testing::fixture("tests/fixtures/**/code.js")]
fn fixture(input: PathBuf) {
let dir = input.parent().unwrap();
let config = read_to_string(dir.join("config.json")).expect("failed to read config.json");
println!("---- Config -----\n{}", config);
let config: Config = serde_json::from_str(&config).unwrap();
test_fixture(
Syntax::Es(EsConfig {
jsx: true,
..Default::default()
}),
&|t| {
//
let fm = t.cm.load_file(&input).unwrap();
chain!(resolver(), styled_components(fm, config.clone()))
},
&input,
&dir.join("output.js"),
)
}
{
"plugins": [
[
"../../../src",
{
"ssr": false,
"fileName": false,
"transpileTemplateLiterals": false
}
]
]
}
\ No newline at end of file
import styled from 'styled-components'
const WithAttrs = styled.div.attrs({ some: 'value' })``
const WithAttrsWrapped = styled(Inner).attrs({ some: 'value' })``
import styled from 'styled-components';
const WithAttrs = styled.div.attrs({
some: 'value'
}).withConfig({
displayName: "WithAttrs"
})``;
const WithAttrsWrapped = styled(Inner).attrs({
some: 'value'
}).withConfig({
displayName: "WithAttrsWrapped"
})``;
import { createGlobalStyle } from 'styled-components'
const GlobalStyle = createGlobalStyle`
body {
color: red;
}
`
import { createGlobalStyle } from 'styled-components';
const GlobalStyle = /*#__PURE__*/createGlobalStyle(["body{color:red;}"]);
import styled, { css } from 'styled-components'
const partial = css`
color: red;
`
const Component = styled.div`
${partial};
background: blue;
`
import styled, { css } from 'styled-components';
const partial = /*#__PURE__*/css(["color:red;"]);
const Component = /*#__PURE__*/styled.div.withConfig({
displayName: "code__Component",
componentId: "sc-4wpzk3-0"
})(["", ";background:blue;"], partial);
import { keyframes } from 'styled-components'
const Animation = keyframes`
0% {
opacity: 0;
}
100% {
opacity: 1;
}
`
import { keyframes } from 'styled-components';
const Animation = /*#__PURE__*/keyframes(["0%{opacity:0;}100%{opacity:1;}"]);
import styled from 'styled-components'
const Test = styled.div`
width: 100%;
`
const Test2 = styled('div')``
const Test3 = true ? styled.div`` : styled.div``
const styles = { One: styled.div`` }
let Component
Component = styled.div``
const WrappedComponent = styled(Inner)``
const StyledObjectForm = styled.div({ color: red })
const StyledFunctionForm = styled.div(p => ({ color: p.color || 'red' }))
const normalFunc = add(5, 3)
import styled from 'styled-components';
const Test = /*#__PURE__*/styled.div.withConfig({
displayName: "code__Test",
componentId: "sc-u20i28-0"
})(["width:100%;"]);
const Test2 = /*#__PURE__*/styled('div').withConfig({
displayName: "code__Test2",
componentId: "sc-u20i28-1"
})([""]);
const Test3 = true ? styled.div.withConfig({
displayName: "code__Test3",
componentId: "sc-u20i28-2"
})([""]) : styled.div.withConfig({
displayName: "code__Test3",
componentId: "sc-u20i28-3"
})([""]);
const styles = {
One: styled.div.withConfig({
displayName: "code__One",
componentId: "sc-u20i28-4"
})([""])
};
let Component;
Component = styled.div.withConfig({
displayName: "code__Component",
componentId: "sc-u20i28-5"
})([""]);
const WrappedComponent = /*#__PURE__*/styled(Inner).withConfig({
displayName: "code__WrappedComponent",
componentId: "sc-u20i28-6"
})([""]);
const StyledObjectForm = /*#__PURE__*/styled.div.withConfig({
displayName: "code__StyledObjectForm",
componentId: "sc-u20i28-7"
})({
color: red
});
const StyledFunctionForm = /*#__PURE__*/styled.div.withConfig({
displayName: "code__StyledFunctionForm",
componentId: "sc-u20i28-8"
})(p => ({
color: p.color || 'red'
}));
const normalFunc = add(5, 3);
import { withTheme } from 'styled-components'
const ThemedComponent = withTheme(() => null)
\ No newline at end of file
import { withTheme } from 'styled-components';
const ThemedComponent = /*#__PURE__*/withTheme(() => null);
import React from "react"
import { css } from "styled-components"
export default function Example() {
return <div css={someCss}>oops</div>
}
const someCss = css`
color: red;
`
import _styled from "styled-components";
import React from "react";
import { css } from "styled-components";
export default function Example() {
return <_StyledDiv>oops</_StyledDiv>;
}
const someCss = css(["color:red;"]);
var _StyledDiv = _styled("div").withConfig({
displayName: "code___StyledDiv",
componentId: "sc-7mydya-0"
})(["", ""], someCss);
{
"plugins": [
[
"../../../src",
{
"ssr": false,
"displayName": false,
"transpileTemplateLiterals": false
}
]
]
}
\ No newline at end of file
import { createGlobalStyle, css, keyframes } from 'styled-components'
const key = keyframes`
to {
transform: rotate(360deg);
}
`
const color = css`
color: ${theColor};
`
const GlobalStyles = createGlobalStyle`
html {
color: red;
}
`
import { createGlobalStyle, css, keyframes } from 'styled-components';
const key = keyframes`to{transform:rotate(360deg);}`;
const color = css`color:${theColor};`;
const GlobalStyles = createGlobalStyle`html{color:red;}`;
{
"presets": [
"@babel/preset-env"
],
"plugins": [
[
"../../../src",
{
"ssr": false,
"displayName": false,
"transpileTemplateLiterals": false
}
]
]
}
\ No newline at end of file
import styled from 'styled-components';
const Simple = styled.div`
width: 100%;
`;
const Interpolation = styled.div`
content: " ${props => props.text} ";
`;
const SpecialCharacters = styled.div`
content: " ${props => props.text} ";\n color: red;
`;
const Comment = styled.div`
// comment
color: red;
`
const Parens = styled.div`
&:hover {
color: blue;
}
`;
"use strict";
var _styledComponents = _interopRequireDefault(require("styled-components"));
var _templateObject, _templateObject2, _templateObject3, _templateObject4, _templateObject5;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
function _taggedTemplateLiteral(strings, raw) { if (!raw) { raw = strings.slice(0); } return Object.freeze(Object.defineProperties(strings, { raw: { value: Object.freeze(raw) } })); }
var Simple = _styledComponents["default"].div(_templateObject || (_templateObject = _taggedTemplateLiteral(["width:100%;"])));
var Interpolation = _styledComponents["default"].div(_templateObject2 || (_templateObject2 = _taggedTemplateLiteral(["content:\" ", " \";"])), function (props) {
return props.text;
});
var SpecialCharacters = _styledComponents["default"].div(_templateObject3 || (_templateObject3 = _taggedTemplateLiteral(["content:\" ", " \";color:red;"])), function (props) {
return props.text;
});
var Comment = _styledComponents["default"].div(_templateObject4 || (_templateObject4 = _taggedTemplateLiteral(["color:red;"])));
var Parens = _styledComponents["default"].div(_templateObject5 || (_templateObject5 = _taggedTemplateLiteral(["&:hover{color:blue;}"])));
{
"plugins": [
[
"../../../src",
{
"ssr": false,
"displayName": false,
"transpileTemplateLiterals": false
}
]
]
}
\ No newline at end of file
import styled from 'styled-components';
const Simple = styled.div`
width: 100%;
`;
const Interpolation = styled.div`
content: "https://test.com/${props => props.endpoint}";
`;
const SpecialCharacters = styled.div`
content: " ${props => props.text} ";\n color: red;
`;
const Comment = styled.div`
width: 100%;
// comment
color: red;
`;
const Parens = styled.div`
&:hover {
color: blue;
}
color: red;
`;
const UrlComments = styled.div`
color: red;
/* // */
background: red;
/* comment 1 */
/* comment 2 */
// comment 3
border: 1px solid green;
`;
import styled from 'styled-components';
const Simple = styled.div`width:100%;`;
const Interpolation = styled.div`content:"https://test.com/${props => props.endpoint}";`;
const SpecialCharacters = styled.div`content:" ${props => props.text} ";color:red;`;
const Comment = styled.div`width:100%;color:red;`;
const Parens = styled.div`&:hover{color:blue;}color:red;`;
const UrlComments = styled.div`color:red;background:red;border:1px solid green;`;
{
"plugins": [
[
"../../../src",
{
"minify": true
}
]
]
}
\ No newline at end of file
import styled from 'styled-components'
const Test1 = styled.div`
width: 100%;
// color: ${'red'};
`
const Test2 = styled.div`
width: 100%;
// color: pale${'red'};
`
const Test3 = styled.div`
width: 100%;
// color
${'red'};
`
const Test4 = styled.div`
width: 100%;
// color: ${'red'}-blue;
`
const Test5 = styled.div`
width: 100%;
// color: ${'red'}${'blue'};
`
const Test6 = styled.div`
background: url("https://google.com");
width: 100%;
${'green'} // color: ${'red'}${'blue'};
`
const Test7 = styled.div`
background: url("https://google.com");
width: ${p => p.props.width};
${'green'} // color: ${'red'}${'blue'};
height: ${p => p.props.height};
`
import styled from 'styled-components';
const Test1 = styled.div.withConfig({
displayName: "code__Test1",
componentId: "sc-kc0mjf-0"
})(["width:100%;"]);
const Test2 = styled.div.withConfig({
displayName: "code__Test2",
componentId: "sc-kc0mjf-1"
})(["width:100%;"]);
const Test3 = styled.div.withConfig({
displayName: "code__Test3",
componentId: "sc-kc0mjf-2"
})(["width:100%;", ";"], 'red');
const Test4 = styled.div.withConfig({
displayName: "code__Test4",
componentId: "sc-kc0mjf-3"
})(["width:100%;"]);
const Test5 = styled.div.withConfig({
displayName: "code__Test5",
componentId: "sc-kc0mjf-4"
})(["width:100%;"]);
const Test6 = styled.div.withConfig({
displayName: "code__Test6",
componentId: "sc-kc0mjf-5"
})(["background:url(\"https://google.com\");width:100%;", " "], 'green');
const Test7 = styled.div.withConfig({
displayName: "code__Test7",
componentId: "sc-kc0mjf-6"
})(["background:url(\"https://google.com\");width:", ";", " height:", ";"], p => p.props.width, 'green', p => p.props.height);
{
"plugins": [
["@babel/plugin-transform-modules-commonjs"],
[
"../../../src"
]
]
}
import React from "react";
import { css } from "styled-components";
import Icons from "./icons";
const someCss = css` background: purple;`;
const App1 = () => { return <Icons css={someCss} />; };
const App2 = () => { return <Icons.Foo css={someCss} />; };
const App3 = () => { return <Icons.Foo.Bar css={someCss} />; };
"use strict";
var _styledComponents = _interopRequireWildcard(require("styled-components"));
var _react = _interopRequireDefault(require("react"));
var _icons = _interopRequireDefault(require("./icons"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
const someCss = (0, _styledComponents.css)([" background:purple;"]);
const App1 = () => {
return <_StyledIcons />;
};
const App2 = () => {
return <_StyledIconsFoo />;
};
const App3 = () => {
return <_StyledIconsFooBar />;
};
var _StyledIcons = (0, _styledComponents.default)(_icons.default).withConfig({
displayName: "code___StyledIcons",
componentId: "sc-1wxehft-0"
})(["", ""], someCss);
var _StyledIconsFoo = (0, _styledComponents.default)(_icons.default.Foo).withConfig({
displayName: "code___StyledIconsFoo",
componentId: "sc-1wxehft-1"
})(["", ""], someCss);
var _StyledIconsFooBar = (0, _styledComponents.default)(_icons.default.Foo.Bar).withConfig({
displayName: "code___StyledIconsFooBar",
componentId: "sc-1wxehft-2"
})(["", ""], someCss);
{
"presets": ["@babel/preset-env"],
"plugins": [
[
"../../../src",
{
"ssr": false,
"displayName": true,
"transpileTemplateLiterals": true,
"minify": false
}
]
]
}
import styled, { css, createGlobalStyle } from 'styled-components'
const Named = styled.div`
width: 100%;
`
const NamedWithInterpolation = styled.div`
color: ${color => props.color};
`
const Wrapped = styled(Inner)`
color: red;
`
const Foo = styled.div({
color: 'green',
})
const style = css`
background: green;
`
const GlobalStyle = createGlobalStyle`
html {
background: silver;
}
`
"use strict";
function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
var _styledComponents = _interopRequireWildcard(require("styled-components"));
function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
var Named = _styledComponents["default"].div.withConfig({
displayName: "code__Named"
})(["\n width: 100%;\n"]);
var NamedWithInterpolation = _styledComponents["default"].div.withConfig({
displayName: "code__NamedWithInterpolation"
})(["\n color: ", ";\n"], function (color) {
return props.color;
});
var Wrapped = (0, _styledComponents["default"])(Inner).withConfig({
displayName: "code__Wrapped"
})(["\n color: red;\n"]);
var Foo = _styledComponents["default"].div.withConfig({
displayName: "code__Foo"
})({
color: 'green'
});
var style = (0, _styledComponents.css)(["\n background: green;\n"]);
var GlobalStyle = (0, _styledComponents.createGlobalStyle)(["\n html {\n background: silver;\n }\n"]);
{
"presets": [
"@babel/preset-env"
],
"plugins": [
[
"../../../src",
{
"ssr": false,
"displayName": false,
"transpileTemplateLiterals": true,
"minify": false
}
]
]
}
\ No newline at end of file
import styled from 'styled-components';
const Named = styled.div`
width: 100%;
`;
const NamedWithInterpolation = styled.div`
color: ${color => props.color};
`;
const Wrapped = styled(Inner)`color: red;`;
"use strict";
var _styledComponents = _interopRequireDefault(require("styled-components"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
var Named = _styledComponents["default"].div(["\n width: 100%;\n"]);
var NamedWithInterpolation = _styledComponents["default"].div(["\n color: ", ";\n"], function (color) {
return props.color;
});
var Wrapped = (0, _styledComponents["default"])(Inner)(["color: red;"]);
{
"plugins": [
[
"../../../src",
{
"transpileTemplateLiterals": false,
"ssr": true
}
]
]
}
\ No newline at end of file
const Test = s.div`width: 100%;`;
import { default as s, css } from 'styled-components';
const Test = s.div.withConfig({
displayName: "code__Test",
componentId: "sc-1dds9bl-0"
})`width:100%;`;
import { default as s, css } from 'styled-components';
import styled from 'styled-components'
const Test = styled.div`
width: 100%;
`
const Test2 = styled('div')``
const Test3 = true ? styled.div`` : styled.div``
const styles = { One: styled.div`` }
let Component
Component = styled.div``
const WrappedComponent = styled(Inner)``
class ClassComponent {
static Child = styled.div``
}
var GoodName = BadName = styled.div``;
{
"ssr": false,
"fileName": false,
"transpileTemplateLiterals": false
}
import styled from 'styled-components';
const Test = styled.div.withConfig({
displayName: "Test"
})`
width: 100%;
`;
const Test2 = styled('div').withConfig({
displayName: "Test2"
})``;
const Test3 = true ? styled.div.withConfig({
displayName: "Test3"
})`` : styled.div.withConfig({
displayName: "Test3"
})``;
const styles = {
One: styled.div.withConfig({
displayName: "One"
})``
};
let Component;
Component = styled.div.withConfig({
displayName: "Component"
})``;
const WrappedComponent = styled(Inner).withConfig({
displayName: "WrappedComponent"
})``;
class ClassComponent {
static Child = styled.div.withConfig({
displayName: "Child"
})``;
}
var GoodName = BadName = styled.div.withConfig({
displayName: "GoodName"
})``;
import styled from 'styled-components'
const Test = styled.div`
width: 100%;
`
const Test2 = true ? styled.div`` : styled.div``
const styles = { One: styled.div`` }
let Component
Component = styled.div``
const WrappedComponent = styled(Inner)``
const WrappedComponent2 = styled.div({})
const WrappedComponent3 = styled(Inner)({})
const WrappedComponent4 = styled(Inner).attrs(() => ({ something: 'else' }))({})
const WrappedComponent5 = styled.div.attrs(() => ({ something: 'else' }))({})
const WrappedComponent6 = styled.div.attrs(() => ({ something: 'else' }))``
const WrappedComponent7 = styled.div.withConfig({
shouldForwardProp: () => {},
})({})
const WrappedComponent8 = styled.div
.withConfig({
shouldForwardProp: () => {},
})
.attrs(() => ({ something: 'else' }))({})
const WrappedComponent9 = styled.div
.attrs(() => ({ something: 'else' }))
.withConfig({
shouldForwardProp: () => {},
})({})
{
"fileName": false,
"transpileTemplateLiterals": false,
"ssr": true
}
import styled from 'styled-components';
const Test = styled.div.withConfig({
displayName: "Test",
componentId: "sc-e0d5b7ad-0"
})`
width: 100%;
`;
const Test2 = true ? styled.div.withConfig({
displayName: "Test2",
componentId: "sc-e0d5b7ad-1"
})`` : styled.div.withConfig({
displayName: "Test2",
componentId: "sc-e0d5b7ad-2"
})``;
const styles = {
One: styled.div.withConfig({
displayName: "One",
componentId: "sc-e0d5b7ad-3"
})``
};
let Component;
Component = styled.div.withConfig({
displayName: "Component",
componentId: "sc-e0d5b7ad-4"
})``;
const WrappedComponent = styled(Inner).withConfig({
displayName: "WrappedComponent",
componentId: "sc-e0d5b7ad-5"
})``;
const WrappedComponent2 = styled.div.withConfig({
displayName: "WrappedComponent2",
componentId: "sc-e0d5b7ad-6"
})({});
const WrappedComponent3 = styled(Inner).withConfig({
displayName: "WrappedComponent3",
componentId: "sc-e0d5b7ad-7"
})({});
const WrappedComponent4 = styled(Inner).attrs(()=>({
something: 'else'
})
)({});
const WrappedComponent5 = styled.div.attrs(()=>({
something: 'else'
})
)({});
const WrappedComponent6 = styled.div.attrs(()=>({
something: 'else'
})
).withConfig({
displayName: "WrappedComponent6",
componentId: "sc-e0d5b7ad-8"
})``;
const WrappedComponent7 = styled.div.withConfig({
shouldForwardProp: ()=>{},
displayName: "WrappedComponent7",
componentId: "sc-e0d5b7ad-9"
})({});
const WrappedComponent8 = styled.div.withConfig({
shouldForwardProp: ()=>{}
}).attrs(()=>({
something: 'else'
})
)({});
const WrappedComponent9 = styled.div.attrs(()=>({
something: 'else'
})
).withConfig({
shouldForwardProp: ()=>{},
displayName: "WrappedComponent9",
componentId: "sc-e0d5b7ad-10"
})({});
import { styled } from '@example/example'
const Test = styled.div`
width: 100%;
`
const Test2 = true ? styled.div`` : styled.div``
const styles = { One: styled.div`` }
let Component
Component = styled.div``
const WrappedComponent = styled(Inner)``
{
"displayName": true,
"fileName": false,
"ssr": true,
"topLevelImportPaths": ["@example/example"],
"transpileTemplateLiterals": false
}
import { styled } from '@example/example';
const Test = styled.div.withConfig({
displayName: "Test",
componentId: "sc-bd3b1624-0"
})`
width: 100%;
`;
const Test2 = true ? styled.div.withConfig({
displayName: "Test2",
componentId: "sc-bd3b1624-1"
})`` : styled.div.withConfig({
displayName: "Test2",
componentId: "sc-bd3b1624-2"
})``;
const styles = {
One: styled.div.withConfig({
displayName: "One",
componentId: "sc-bd3b1624-3"
})``
};
let Component;
Component = styled.div.withConfig({
displayName: "Component",
componentId: "sc-bd3b1624-4"
})``;
const WrappedComponent = styled(Inner).withConfig({
displayName: "WrappedComponent",
componentId: "sc-bd3b1624-5"
})``;
import styled from '@xstyled/styled-components'
const Test = styled.div`
width: 100%;
`
const Test2 = true ? styled.div`` : styled.div``
const styles = { One: styled.div`` }
let Component
Component = styled.div``
const WrappedComponent = styled(Inner)``
{
"displayName": false,
"fileName": false,
"ssr": true,
"topLevelImportPaths": [
"@xstyled/styled-components",
"@xstyled/styled-components/no-tags",
"@xstyled/styled-components/native",
"@xstyled/styled-components/primitives"
],
"transpileTemplateLiterals": false
}
import styled from '@xstyled/styled-components';
const Test = styled.div.withConfig({
componentId: "sc-2fd35b87-0"
})`
width: 100%;
`;
const Test2 = true ? styled.div.withConfig({
componentId: "sc-2fd35b87-1"
})`` : styled.div.withConfig({
componentId: "sc-2fd35b87-2"
})``;
const styles = {
One: styled.div.withConfig({
componentId: "sc-2fd35b87-3"
})``
};
let Component;
Component = styled.div.withConfig({
componentId: "sc-2fd35b87-4"
})``;
const WrappedComponent = styled(Inner).withConfig({
componentId: "sc-2fd35b87-5"
})``;
import styled from 'styled-components'
const Test = styled.div`
width: 100%;
`
const Test2 = true ? styled.div`` : styled.div``
const styles = { One: styled.div`` }
let Component
Component = styled.div``
const WrappedComponent = styled(Inner)``
{
"displayName": false,
"fileName": false,
"transpileTemplateLiterals": false,
"ssr": true
}
import styled from 'styled-components';
const Test = styled.div.withConfig({
componentId: "sc-bc9ba4b0-0"
})`
width: 100%;
`;
const Test2 = true ? styled.div.withConfig({
componentId: "sc-bc9ba4b0-1"
})`` : styled.div.withConfig({
componentId: "sc-bc9ba4b0-2"
})``;
const styles = {
One: styled.div.withConfig({
componentId: "sc-bc9ba4b0-3"
})``
};
let Component;
Component = styled.div.withConfig({
componentId: "sc-bc9ba4b0-4"
})``;
const WrappedComponent = styled(Inner).withConfig({
componentId: "sc-bc9ba4b0-5"
})``;
const domElements = ['div']
const styled = () => {}
domElements.forEach(domElement => {
styled[domElement] = styled(domElement)
})
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment