Skip to content

Commit

Permalink
fix(css): Expose modules mapping (#39)
Browse files Browse the repository at this point in the history
  • Loading branch information
kdy1 authored Jul 24, 2023
1 parent 78d9753 commit 41c57b1
Show file tree
Hide file tree
Showing 4 changed files with 60 additions and 8 deletions.
55 changes: 51 additions & 4 deletions crates/css_node/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
#[macro_use]
extern crate napi_derive;

use std::{backtrace::Backtrace, env, fmt::Write, panic::set_hook, sync::Arc};
use std::{
backtrace::Backtrace, collections::HashMap, env, fmt::Write, panic::set_hook, sync::Arc,
};

use anyhow::{bail, Context};
use napi::{bindgen_prelude::*, Task};
Expand Down Expand Up @@ -54,6 +56,10 @@ pub struct TransformOutput {
/// JSON string.
#[serde(skip_serializing_if = "Option::is_none")]
pub deps: Option<String>,

/// JSON string.
#[serde(skip_serializing_if = "Option::is_none")]
pub modules_mapping: Option<String>,
}

struct MinifyTask {
Expand Down Expand Up @@ -120,6 +126,14 @@ enum CssClassNameSegment {
Hash,
}

#[derive(Serialize)]
#[serde(tag = "type")]
pub enum CssClassName {
Local { name: JsWord },
Global { name: JsWord },
Import { name: JsWord, from: JsWord },
}

impl swc_css_modules::TransformConfig for CssModuleTransformConfig {
fn new_name_for(&self, local: &JsWord) -> JsWord {
let mut buf = String::new();
Expand Down Expand Up @@ -326,6 +340,7 @@ fn minify_inner(code: &str, opts: MinifyOptions) -> anyhow::Result<TransformOutp
map,
errors: returned_errors,
deps: Default::default(),
modules_mapping: Default::default(),
})
})
}
Expand Down Expand Up @@ -394,8 +409,8 @@ fn transform_inner(code: &str, opts: TransformOptions) -> anyhow::Result<Transfo
}
}

if let Some(config) = opts.css_modules {
swc_css_modules::compile(
let modules_mapping = if let Some(config) = opts.css_modules {
let result = swc_css_modules::compile(
&mut ss,
CssModuleTransformConfig {
file_name: Arc::new(fm.name.clone()),
Expand All @@ -405,7 +420,38 @@ fn transform_inner(code: &str, opts: TransformOptions) -> anyhow::Result<Transfo
.context("failed to parse the pattern for CSS Modules")?,
},
);
}
let map: HashMap<_, _> = result
.renamed
.into_iter()
.map(|(k, v)| {
(
k,
v.into_iter()
.map(|v| match v {
swc_css_modules::CssClassName::Local { name } => {
CssClassName::Local { name: name.value }
}
swc_css_modules::CssClassName::Global { name } => {
CssClassName::Global { name: name.value }
}
swc_css_modules::CssClassName::Import { name, from } => {
CssClassName::Import {
name: name.value,
from,
}
}
})
.collect::<Vec<_>>(),
)
})
.collect();
Some(
serde_json::to_string(&map)
.context("failed to serialize the mapping for CSS Modules")?,
)
} else {
None
};

ss.visit_mut_with(&mut Compiler::new(Config {
// TODO: preset-env
Expand Down Expand Up @@ -461,6 +507,7 @@ fn transform_inner(code: &str, opts: TransformOptions) -> anyhow::Result<Transfo
map,
errors: returned_errors,
deps: deps.map(|v| serde_json::to_string(&v).unwrap()),
modules_mapping,
})
})
}
Expand Down
2 changes: 2 additions & 0 deletions packages/css/binding.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ export interface TransformOutput {
errors?: Array<Diagnostic>
/** JSON string. */
deps?: string
/** JSON string. */
modulesMapping?: string
}
export function minify(code: Buffer, opts: Buffer, signal?: AbortSignal | undefined | null): Promise<TransformOutput>
export function minifySync(code: Buffer, opts: Buffer): TransformOutput
Expand Down
2 changes: 1 addition & 1 deletion packages/css/binding.js
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,7 @@ switch (platform) {
nativeBinding = require('@swc/css-darwin-universal')
}
break
} catch {}
} catch { }
switch (arch) {
case 'x64':
localFileExisted = existsSync(join(__dirname, 'css.darwin-x64.node'))
Expand Down
9 changes: 6 additions & 3 deletions packages/css/examples/deps.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,12 @@ const css = `
`;

async function main() {
const output = swc.transformSync(Buffer.from(css), {
analyzeDependencies: true
const output = await swc.transform(Buffer.from(css), {
analyzeDependencies: true,
cssModules: {
pattern: "[name]-[local]-[hash]",
},
});
console.log(output.deps);
console.log(output);
}
main();

0 comments on commit 41c57b1

Please sign in to comment.