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

support styled_components_plugin #896

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
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
154 changes: 87 additions & 67 deletions Cargo.lock

Large diffs are not rendered by default.

2 changes: 2 additions & 0 deletions crates/core/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,8 @@ swc_core = { workspace = true, features = [
swc_error_reporters = "0.17.12"
swc_node_comments = "0.20.12"
swc_emotion = "0.67.0"
swc_common = "=0.33.12"
styled_components = "0.87.0"

base64 = "0.21.2"
petgraph = "0.6.3"
Expand Down
6 changes: 3 additions & 3 deletions crates/core/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,9 +24,9 @@ pub use {
anyhow, base64, cached, clap, colored, config, convert_case, fs_extra, futures, glob, hyper,
hyper_staticfile, hyper_tungstenite, indexmap, lazy_static, md5, mdxjs, merge_source_map,
mime_guess, nodejs_resolver, notify, notify_debouncer_full, path_clean, pathdiff, petgraph,
rayon, regex, sailfish, serde, serde_json, serde_xml_rs, serde_yaml, svgr_rs, swc_emotion,
swc_error_reporters, swc_node_comments, thiserror, tokio, tokio_tungstenite, toml, tracing,
tracing_subscriber, tungstenite, twox_hash,
rayon, regex, sailfish, serde, serde_json, serde_xml_rs, serde_yaml, styled_components,
svgr_rs, swc_emotion, swc_error_reporters, swc_node_comments, thiserror, tokio,
tokio_tungstenite, toml, tracing, tracing_subscriber, tungstenite, twox_hash,
};

#[macro_export]
Expand Down
1 change: 1 addition & 0 deletions crates/mako/src/compiler.rs
Original file line number Diff line number Diff line change
Expand Up @@ -255,6 +255,7 @@ impl Compiler {
Arc::new(plugins::wasm_runtime::WasmRuntimePlugin {}),
Arc::new(plugins::async_runtime::AsyncRuntimePlugin {}),
Arc::new(plugins::emotion::EmotionPlugin {}),
Arc::new(plugins::styled_components::StyledComponentsPlugin {}),
Arc::new(plugins::node_stuff::NodeStuffPlugin {}),
];
plugins.extend(builtin_plugins);
Expand Down
35 changes: 35 additions & 0 deletions crates/mako/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,10 @@ use serde::Serialize;
use crate::plugins::node_polyfill::get_all_modules;
use crate::{optimize_chunk, plugins, transformers};

fn true_by_default() -> bool {
true
}

#[derive(Debug, Diagnostic)]
#[diagnostic(code("mako.config.json parsed failed"))]
struct ConfigParseError {
Expand Down Expand Up @@ -99,6 +103,7 @@ create_deserialize_fn!(deserialize_devtool, DevtoolConfig);
create_deserialize_fn!(deserialize_tree_shaking, TreeShakingStrategy);
create_deserialize_fn!(deserialize_optimization, OptimizationConfig);
create_deserialize_fn!(deserialize_minifish, MinifishConfig);
create_deserialize_fn!(deserialize_styled_components, StyledComponentsConfig);

#[derive(Deserialize, Serialize, Debug)]
#[serde(rename_all = "camelCase")]
Expand Down Expand Up @@ -351,6 +356,30 @@ pub struct HmrConfig {
pub host: String,
pub port: u16,
}
#[derive(Deserialize, Serialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct StyledComponentsConfig {
#[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 meaningless_file_names: Vec<String>,
#[serde(default)]
pub top_level_import_paths: Vec<String>,
#[serde(default)]
pub namespace: String,
#[serde(default)]
pub transpile_template_literals: bool,
#[serde(default)]
pub minify: bool,
#[serde(default)]
pub pure: bool,
#[serde(default = "true_by_default")]
pub css_prop: bool,
}

#[derive(Deserialize, Serialize, Debug)]
#[serde(rename_all = "camelCase")]
Expand Down Expand Up @@ -407,6 +436,11 @@ pub struct Config {
#[serde(rename = "optimizePackageImports")]
pub optimize_package_imports: bool,
pub emotion: bool,
#[serde(
rename = "styledComponents",
deserialize_with = "deserialize_styled_components"
)]
pub styled_components: Option<StyledComponentsConfig>,
pub flex_bugs: bool,
#[serde(deserialize_with = "deserialize_optimization")]
pub optimization: Option<OptimizationConfig>,
Expand Down Expand Up @@ -560,6 +594,7 @@ const DEFAULT_CONFIG: &str = r#"
"ignores": [],
"optimizePackageImports": false,
"emotion": false,
"styledComponents": false,
"flexBugs": false,
"cjs": false,
"optimization": { "skipModules": true },
Expand Down
1 change: 1 addition & 0 deletions crates/mako/src/plugins/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ pub mod node_polyfill;
pub mod node_stuff;
pub mod raw;
pub mod runtime;
pub mod styled_components;
pub mod svg;
pub mod toml;
pub mod wasm;
Expand Down
55 changes: 55 additions & 0 deletions crates/mako/src/plugins/styled_components.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
use std::sync::Arc;

use mako_core::anyhow::Result;
use mako_core::styled_components::{styled_components, Config};
use mako_core::swc_common::FileName;
use mako_core::swc_ecma_ast::Module;
use mako_core::swc_ecma_visit::VisitMutWith;

use crate::compiler::Context;
use crate::plugin::{Plugin, PluginTransformJsParam};

pub struct StyledComponentsPlugin {}

impl Plugin for StyledComponentsPlugin {
fn name(&self) -> &str {
"styled_components"
}

fn transform_js(
&self,
param: &PluginTransformJsParam,
ast: &mut Module,
context: &Arc<Context>,
) -> Result<()> {
if context.config.styled_components.is_some() {
let raw_config = context.config.styled_components.as_ref().unwrap();
let pos = context.meta.script.cm.lookup_char_pos(ast.span.lo);
let hash = pos.file.src_hash;
let mut styled_visitor = styled_components(
FileName::Real(param.path.into()),
hash,
Config {
display_name: raw_config.display_name,
ssr: raw_config.ssr,
file_name: raw_config.file_name,
meaningless_file_names: raw_config.meaningless_file_names.clone(),
namespace: raw_config.namespace.clone(),
transpile_template_literals: raw_config.transpile_template_literals,
minify: raw_config.minify,
pure: raw_config.pure,
css_prop: raw_config.css_prop,
top_level_import_paths: raw_config
.top_level_import_paths
.clone()
.into_iter()
.map(|s| s.into())
.collect(),
},
);
ast.visit_mut_with(&mut styled_visitor);
}

Ok(())
}
}
35 changes: 35 additions & 0 deletions examples/with-styled-components/index.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import React from 'react';
import ReactDOM from 'react-dom/client';
import styled from 'styled-components';

const DivContainer = styled.div({
background: 'red',
});

const SpanContainer = styled('span')({
background: 'yellow',
});

const Child = styled.div`
color: red;
`;

const Parent = styled.div`
${Child} {
color: green;
}
`;

const App = () => {
return [
'3333',
<DivContainer>red div</DivContainer>,
<SpanContainer>yellow span</SpanContainer>,
<Parent>
<Child>Green because I am inside a Parent</Child>
</Parent>,
<Child>Red because I am not inside a Parent</Child>,
];
};

ReactDOM.createRoot(document.getElementById('root')).render(<App />);
8 changes: 8 additions & 0 deletions examples/with-styled-components/mako.config.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"styledComponents": {
"namespace": "mako_app"
},
"optimization": {},
"minify": false,
"moduleIdStrategy": "named"
}
10 changes: 10 additions & 0 deletions examples/with-styled-components/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
{
"scripts": {
"build": "cargo run -- $PWD"
},
"dependencies": {
"react": "18.2.0",
"react-dom": "18.2.0",
"styled-components": "^5.3.10"
}
}
12 changes: 12 additions & 0 deletions examples/with-styled-components/public/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
<!DOCTYPE html>
<html lang="en">

<head>
</head>

<body>
<div id="root"></div>
<script src="index.js"></script>
</body>

</html>
Loading