Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: implement styled_components visitor #4228

Merged
merged 6 commits into from
Oct 8, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 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 @@ -54,6 +54,7 @@ napi = { version = "=2.12.5" }
napi-build = { version = "=2.0.1" }
napi-derive = { version = "=2.12.3" }
napi-sys = { version = "=2.2.3" }
styled_components = { version = "=0.72.0" }
swc_config = { version = "=0.1.7" }
swc_core = { version = "=0.83.1", default-features = false }
swc_css = { version = "=0.155.2" }
Expand Down
1 change: 1 addition & 0 deletions crates/rspack_loader_swc/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ version = "0.1.0"
anyhow = { workspace = true }
async-trait = { workspace = true }
either = "1"
once_cell = { workspace = true }
rspack_core = { path = "../rspack_core" }
rspack_error = { path = "../rspack_error" }
rspack_loader_runner = { path = "../rspack_loader_runner" }
Expand Down
13 changes: 3 additions & 10 deletions crates/rspack_loader_swc/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@ use swc_core::common::{
comments::SingleThreadedComments, FileName, FilePathMapping, Mark, GLOBALS,
};
use swc_core::ecma::transforms::base::pass::noop;
use xxhash_rust::xxh32::xxh32;

mod options;
mod transformer;
Expand Down Expand Up @@ -101,18 +100,12 @@ impl Loader<LoaderRunnerContext> for SwcLoader {
let unresolved_mark = Mark::new();
swc_options.top_level_mark = Some(top_level_mark);
swc_options.unresolved_mark = Some(unresolved_mark);
let source = content.try_into_string()?;
let content = content.try_into_string()?;
let rspack_options = &*loader_context.context.options;
let source_content_hash = self
.options_with_additional
.rspack_experiments
.emotion
.as_ref()
.map(|_| xxh32(source.as_bytes(), 0));

let fm = c
.cm
.new_source_file(FileName::Real(resource_path.clone()), source);
.new_source_file(FileName::Real(resource_path.clone()), content.clone());
let comments = SingleThreadedComments::default();

let out = c.process_js_with_custom_pass(
Expand All @@ -129,7 +122,7 @@ impl Loader<LoaderRunnerContext> for SwcLoader {
top_level_mark,
unresolved_mark,
c.cm.clone(),
source_content_hash,
content,
&self.options_with_additional.rspack_experiments,
)
},
Expand Down
6 changes: 5 additions & 1 deletion crates/rspack_loader_swc/src/options.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
use rspack_swc_visitors::{
EmotionOptions, ImportOptions, RawEmotionOptions, RawImportOptions, RawRelayOptions, RelayOptions,
EmotionOptions, ImportOptions, RawEmotionOptions, RawImportOptions, RawRelayOptions,
RawStyledComponentsOptions, RelayOptions, StyledComponentsOptions,
};
use serde::Deserialize;
use swc_config::config_types::BoolConfig;
Expand All @@ -12,13 +13,15 @@ use swc_core::base::config::{
#[serde(rename_all = "camelCase", default)]
pub struct RawRspackExperiments {
pub relay: Option<RawRelayOptions>,
pub styled_components: Option<RawStyledComponentsOptions>,
pub import: Option<Vec<RawImportOptions>>,
pub emotion: Option<RawEmotionOptions>,
}

#[derive(Default, Debug)]
pub(crate) struct RspackExperiments {
pub(crate) relay: Option<RelayOptions>,
pub(crate) styled_components: Option<StyledComponentsOptions>,
pub(crate) import: Option<Vec<ImportOptions>>,
pub(crate) emotion: Option<EmotionOptions>,
}
Expand All @@ -27,6 +30,7 @@ impl From<RawRspackExperiments> for RspackExperiments {
fn from(value: RawRspackExperiments) -> Self {
Self {
relay: value.relay.map(|v| v.into()),
styled_components: value.styled_components.map(|v| v.into()),
import: value
.import
.map(|i| i.into_iter().map(|v| v.into()).collect()),
Expand Down
21 changes: 17 additions & 4 deletions crates/rspack_loader_swc/src/transformer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,13 @@ use std::path::{Path, PathBuf};
use std::sync::Arc;

use either::Either;
use once_cell::sync::Lazy;
use rspack_core::CompilerOptions;
use rspack_swc_visitors::{styled_components, StyledComponentsOptions};
use swc_core::common::FileName;
use swc_core::common::{chain, comments::Comments, Mark, SourceMap};
use swc_core::ecma::{transforms::base::pass::noop, visit::Fold};
use xxhash_rust::xxh32::xxh32;

use crate::options::RspackExperiments;

Expand Down Expand Up @@ -33,23 +37,32 @@ pub(crate) fn transform<'a>(
_top_level_mark: Mark,
unresolved_mark: Mark,
cm: Arc<SourceMap>,
content_hash: Option<u32>,
content: String,
rspack_experiments: &'a RspackExperiments,
) -> impl Fold + 'a {
use rspack_swc_visitors::EmotionOptions;
let content_hash = Lazy::new(|| xxh32(content.as_bytes(), 0));

chain!(
either!(rspack_experiments.emotion, |options: &EmotionOptions| {
// SAFETY: Source content hash should always available if emotion is turned on.
let content_hash = content_hash.expect("Content hash should be available");
rspack_swc_visitors::emotion(
options.clone(),
resource_path,
content_hash,
*content_hash,
cm.clone(),
comments,
)
}),
either!(
rspack_experiments.styled_components,
|options: &StyledComponentsOptions| {
styled_components(
FileName::Real(resource_path.into()),
(*content_hash).into(),
options.clone(),
)
}
),
either!(rspack_experiments.relay, |options| {
rspack_swc_visitors::relay(
options,
Expand Down
1 change: 1 addition & 0 deletions crates/rspack_swc_visitors/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ indexmap = { workspace = true }
once_cell = { workspace = true }
regex = { workspace = true }
serde = { workspace = true, features = ["derive"] }
styled_components = { workspace = true }
swc_core = { workspace = true, features = ["ecma_ast"] }
swc_emotion = { workspace = true }
swc_plugin_import = { path = "../swc_plugin_import" }
Expand Down
5 changes: 5 additions & 0 deletions crates/rspack_swc_visitors/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,3 +15,8 @@ pub use import::{import, CustomTransform, ImportOptions, RawImportOptions, Style

mod emotion;
pub use emotion::{emotion, EmotionOptions, RawEmotionOptions};

mod styled_components;
pub use crate::styled_components::{
styled_components, RawStyledComponentsOptions, StyledComponentsOptions,
};
43 changes: 43 additions & 0 deletions crates/rspack_swc_visitors/src/styled_components.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
use serde::Deserialize;
pub use styled_components::styled_components;

pub type StyledComponentsOptions = styled_components::Config;

#[derive(Deserialize, Debug, Clone)]
#[serde(rename_all = "camelCase")]
pub struct RawStyledComponentsOptions {
pub display_name: Option<bool>,
pub ssr: Option<bool>,
pub file_name: Option<bool>,
pub meaningless_file_names: Option<Vec<String>>,
pub namespace: Option<String>,
pub top_level_import_paths: Option<Vec<String>>,
pub transpile_template_literals: Option<bool>,
pub minify: Option<bool>,
pub pure: Option<bool>,
pub css_prop: Option<bool>,
}

impl From<RawStyledComponentsOptions> for StyledComponentsOptions {
fn from(raw_config: RawStyledComponentsOptions) -> Self {
Self {
display_name: raw_config.display_name.unwrap_or(true),
ssr: raw_config.ssr.unwrap_or(true),
file_name: raw_config.file_name.unwrap_or(true),
meaningless_file_names: raw_config
.meaningless_file_names
.unwrap_or_else(|| vec!["index".to_string()]),
namespace: raw_config.namespace.unwrap_or_default(),
top_level_import_paths: raw_config
.top_level_import_paths
.unwrap_or_default()
.into_iter()
.map(|s| s.into())
.collect(),
transpile_template_literals: raw_config.transpile_template_literals.unwrap_or_default(),
minify: raw_config.minify.unwrap_or_default(),
pure: raw_config.pure.unwrap_or_default(),
css_prop: raw_config.css_prop.unwrap_or(true),
}
}
}
1 change: 1 addition & 0 deletions packages/rspack/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@
"postcss-pxtorem": "^6.0.0",
"pug-loader": "^2.4.0",
"react-relay": "^14.1.0",
"styled-components": "^6.0.8",
"sass": "^1.56.2",
"sass-loader": "^13.2.0",
"source-map": "^0.7.4",
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
// @ts-ignore
import styled from "@xstyled/styled-components";
import React from "react";

export const Button = () => {
return (
<Container>
{/* @ts-ignore */}
<div css={{ color: "red" }}>Hello, Rspack!</div>
</Container>
);
};

export const Container = styled.div`
padding: 2rem;
background-color: pink;
`;
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { Container } from "./Button";

it("styled components", () => {
console.log(Container.componentStyle);
expect(Container.displayName).toMatch("Button__Container");
expect(Container.styledComponentId).toMatch(
/^Button__Container-rspack-test__/
);
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
/** @type {import('@rspack/core').Configuration}*/
module.exports = {
resolve: {
alias: {
"@xstyled/styled-components": "styled-components"
}
},
module: {
rules: [
{
test: /\.jsx?$/,
loader: "builtin:swc-loader",
options: {
jsc: {
parser: {
syntax: "ecmascript",
jsx: true
}
},
rspackExperiments: {
styledComponents: {
displayName: true,
ssr: true,
fileName: true,
meaninglessFileNames: ["index", "styles"],
namespace: "rspack-test",
topLevelImportPaths: [
"@xstyled/styled-components",
"@xstyled/styled-components/*"
],
transpileTemplateLiterals: true,
minify: true,
pure: true,
cssProps: true
}
}
}
}
]
}
};
Loading
Loading