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: add emit_assets and css_modules_export_only_locales config #890

Merged
merged 1 commit into from
Jan 23, 2024
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
5 changes: 5 additions & 0 deletions crates/mako/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -411,6 +411,9 @@ pub struct Config {
#[serde(deserialize_with = "deserialize_optimization")]
pub optimization: Option<OptimizationConfig>,
pub react: ReactConfig,
pub emit_assets: bool,
#[serde(rename = "cssModulesExportOnlyLocales")]
pub css_modules_export_only_locales: bool,
}

pub(crate) fn hash_config(c: &Config) -> u64 {
Expand Down Expand Up @@ -566,6 +569,8 @@ const DEFAULT_CONFIG: &str = r#"
"runtime": "automatic",
"pragmaFrag": "React.Fragment"
},
"emitAssets": true,
"cssModulesExportOnlyLocales": false,
}
"#;

Expand Down
30 changes: 15 additions & 15 deletions crates/mako/src/generate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -103,24 +103,25 @@ impl Compiler {
let (t_generate_chunks, t_ast_to_code_and_write) = self.write_chunk_files(full_hash)?;

// write assets
let t_write_assets = Instant::now();
debug!("write assets");
// why {} block? unlock assets_info
{
let assets_info = &(*self.context.assets_info.lock().unwrap());
for (k, v) in assets_info {
let asset_path = &self.context.root.join(k);
let asset_output_path = &config.output.path.join(v);
if asset_path.exists() {
fs::copy(asset_path, asset_output_path)?;
} else {
return Err(anyhow!("asset not found: {}", asset_path.display()));
if config.emit_assets {
let t_write_assets = Instant::now();
debug!("write assets");
{
let assets_info = &(*self.context.assets_info.lock().unwrap());
for (k, v) in assets_info {
let asset_path = &self.context.root.join(k);
let asset_output_path = &config.output.path.join(v);
if asset_path.exists() {
fs::copy(asset_path, asset_output_path)?;
} else {
return Err(anyhow!("asset not found: {}", asset_path.display()));
}
}
}
let t_write_assets = t_write_assets.elapsed();
debug!(" - write assets: {}ms", t_write_assets.as_millis());
}

let t_write_assets = t_write_assets.elapsed();

// generate stats
let stats = create_stats_info(0, self);
if self.context.config.stats && !self.context.args.watch {
Expand Down Expand Up @@ -150,7 +151,6 @@ impl Compiler {
" - ast to code and write: {}ms",
t_ast_to_code_and_write.as_millis()
);
debug!(" - write assets: {}ms", t_write_assets.as_millis());

Ok(())
}
Expand Down
31 changes: 24 additions & 7 deletions crates/mako/src/plugins/css.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,11 @@ impl Plugin for CSSPlugin {
import_url_to_href(&mut ast);
// parse css module as js
if has_asmodule_query {
let code = generate_code_for_css_modules(&param.task.request.path, &mut ast);
let code = generate_code_for_css_modules(
&param.task.request.path,
&mut ast,
context.config.css_modules_export_only_locales,
);
let js_ast = build_js_ast(&param.task.request.path, &code, context)?;
return Ok(Some(ModuleAst::Script(js_ast)));
} else {
Expand Down Expand Up @@ -111,7 +115,11 @@ fn compile_css_modules(path: &str, ast: &mut Stylesheet) -> TransformResult {
)
}

fn generate_code_for_css_modules(path: &str, ast: &mut Stylesheet) -> String {
fn generate_code_for_css_modules(
path: &str,
ast: &mut Stylesheet,
css_modules_export_only_locales: bool,
) -> String {
let stylesheet = compile_css_modules(path, ast);

let mut export_names = Vec::new();
Expand Down Expand Up @@ -140,13 +148,22 @@ fn generate_code_for_css_modules(path: &str, ast: &mut Stylesheet) -> String {
.collect::<Vec<String>>()
.join(",");

format!(
r#"
if css_modules_export_only_locales {
format!(
r#"
export default {{{}}}
"#,
export_names
)
} else {
format!(
r#"
import "{}?modules";
export default {{{}}}
"#,
path, export_names
)
path, export_names
)
}
}

// Why do this?
Expand Down Expand Up @@ -307,7 +324,7 @@ export default {"a": `a-hlnPCer-`,"b": `b-KOXpblx_ a`,"c": `c-WTxpkVWA c`}
let path = "/test/path";
let mut ast = build_css_ast(path, code, &Arc::new(Default::default()), true).unwrap();

generate_code_for_css_modules(path, &mut ast)
generate_code_for_css_modules(path, &mut ast, false)
}

#[test]
Expand Down
4 changes: 4 additions & 0 deletions crates/node/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,8 @@ export interface BuildParams {
ignoreCSSParserErrors?: boolean;
dynamicImportToRequire?: boolean;
umd?: false | string;
cjs?: boolean;
writeToDisk?: boolean;
transformImport?: {
libraryName: string;
libraryDirectory?: string;
Expand Down Expand Up @@ -127,6 +129,8 @@ export interface BuildParams {
importSource?: string;
pragmaFrag?: string;
};
emitAssets: boolean;
cssModulesExportOnlyLocales: boolean;
};
hooks: JsHooks;
watch: boolean;
Expand Down
4 changes: 4 additions & 0 deletions crates/node/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,8 @@ pub struct BuildParams {
ignoreCSSParserErrors?: boolean;
dynamicImportToRequire?: boolean;
umd?: false | string;
cjs?: boolean;
writeToDisk?: boolean;
transformImport?: { libraryName: string; libraryDirectory?: string; style?: boolean | string }[];
clean?: boolean;
nodePolyfill?: boolean;
Expand All @@ -109,6 +111,8 @@ pub struct BuildParams {
importSource?: string;
pragmaFrag?: string;
};
emitAssets: boolean;
cssModulesExportOnlyLocales: boolean;
}"#)]
pub config: serde_json::Value,
pub hooks: JsHooks,
Expand Down
14 changes: 14 additions & 0 deletions docs/config.md
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,13 @@

需要拷贝的文件或目录,默认会拷贝 `public` 目录下的文件到输出目录。

## cssModulesExportOnlyLocales

- 类型:`boolean`
- 默认值:`false`

是否只导出 CSS Modules 的类名,而不导出 CSS Modules 的值。通常用于服务端渲染场景,因为服务端渲染时不需要 CSS Modules 的值,只需要类名即可。

## define

- 类型:`Record<string, string>`
Expand Down Expand Up @@ -111,6 +118,13 @@ import("./a.js")
// => require("./a.js")
```

## emitAssets

- 类型:`boolean`
- 默认值:`true`

是否输出 assets 文件。通常用于构建纯服务端渲染的项目时设置为 `false`,因为此时不需要输出 assets 文件。

## emotion

- 类型:`boolean`
Expand Down
10 changes: 10 additions & 0 deletions e2e/fixtures/config.css_modules_export_only_locales/expect.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
const assert = require("assert");
const { parseBuildResult, moduleReg } = require("../../../scripts/test-utils");
const { files } = parseBuildResult(__dirname);

const filePaths = Object.keys(files);
const hasCSS = filePaths.some((path) => path.endsWith(".css"));
assert(!hasCSS, "should not emit css");

let content = files["index.js"];
assert(content.includes(`"foo": \`foo-`), 'should contain css modules map');
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"minify": false,
"platform": "node",
"cssModulesExportOnlyLocales": true
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
.foo {
color: red;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
import x from './index.module.css';
export const foo = x;
7 changes: 7 additions & 0 deletions e2e/fixtures/config.emit_assets.false/expect.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
const assert = require("assert");
const { parseBuildResult, moduleReg } = require("../../../scripts/test-utils");
const { files } = parseBuildResult(__dirname);

const filePaths = Object.keys(files);
const hasImage = filePaths.some((path) => path.endsWith(".jpg"));
assert(!hasImage, "should not emit image");
5 changes: 5 additions & 0 deletions e2e/fixtures/config.emit_assets.false/mako.config.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"minify": false,
"platform": "node",
"emitAssets": false
}
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
3 changes: 3 additions & 0 deletions e2e/fixtures/config.emit_assets.false/src/index.module.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
.foo {
color: red;
}
2 changes: 2 additions & 0 deletions e2e/fixtures/config.emit_assets.false/src/index.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
import x from './big_image.jpg';
export const foo = x;