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: supports umd export #1723

Merged
merged 5 commits into from
Dec 16, 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
2 changes: 1 addition & 1 deletion crates/binding/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,7 @@ pub struct BuildParams {
autoCSSModules?: boolean;
ignoreCSSParserErrors?: boolean;
dynamicImportToRequire?: boolean;
umd?: false | string;
umd?: false | string | { name: string, export?: string[] };
cjs?: boolean;
writeToDisk?: boolean;
transformImport?: { libraryName: string; libraryDirectory?: string; style?: boolean | string }[];
Expand Down
8 changes: 6 additions & 2 deletions crates/mako/src/config/output.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ use clap::ValueEnum;
use serde::{Deserialize, Serialize};
use swc_core::ecma::ast::EsVersion;

use super::Umd;
use crate::create_deserialize_fn;
use crate::utils::get_pkg_name;

Expand Down Expand Up @@ -49,8 +50,11 @@ impl fmt::Display for CrossOriginLoading {
}
}

pub fn get_default_chunk_loading_global(umd: Option<String>, root: &Path) -> String {
let unique_name = umd.unwrap_or_else(|| get_pkg_name(root).unwrap_or("global".to_string()));
pub fn get_default_chunk_loading_global(umd: Option<Umd>, root: &Path) -> String {
let unique_name = umd.map_or_else(
|| get_pkg_name(root).unwrap_or("global".to_string()),
|umd| umd.name.clone(),
);

format!("makoChunk_{}", unique_name)
}
Expand Down
33 changes: 28 additions & 5 deletions crates/mako/src/config/umd.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,30 @@
use serde::Deserialize;
use serde::{Deserialize, Serialize};

use crate::create_deserialize_fn;
#[derive(Debug, Deserialize, Serialize, Clone, Default)]
pub struct Umd {
pub name: String,
#[serde(default)]
pub export: Vec<String>,
}

pub type Umd = String;

create_deserialize_fn!(deserialize_umd, Umd);
pub fn deserialize_umd<'de, D>(deserializer: D) -> Result<Option<Umd>, D::Error>
where
D: serde::Deserializer<'de>,
{
let value: serde_json::Value = serde_json::Value::deserialize(deserializer)?;
match value {
serde_json::Value::Object(obj) => Ok(Some(
serde_json::from_value::<Umd>(serde_json::Value::Object(obj))
.map_err(serde::de::Error::custom)?,
)),
serde_json::Value::String(name) => Ok(Some(Umd {
name,
..Default::default()
})),
_ => Err(serde::de::Error::custom(format!(
"invalid `{}` value: {}",
stringify!(deserialize_umd).replace("deserialize_", ""),
value
))),
}
}
9 changes: 8 additions & 1 deletion crates/mako/src/generate/chunk_pot/util.rs
Original file line number Diff line number Diff line change
Expand Up @@ -95,14 +95,21 @@ pub(crate) fn empty_module_fn_expr() -> FnExpr {
}

pub(crate) fn runtime_code(context: &Arc<Context>) -> Result<String> {
let umd = context.config.umd.clone();
let umd = context.config.umd.as_ref().map(|umd| umd.name.clone());
let umd_export = context.config.umd.as_ref().map_or(vec![], |umd| {
umd.export
.iter()
.map(|e| format!("[{}]", serde_json::to_string(e).unwrap()))
.collect()
});
let chunk_graph = context.chunk_graph.read().unwrap();
let has_dynamic_chunks = chunk_graph.get_all_chunks().len() > 1;
let has_hmr = context.args.watch;
let app_runtime = AppRuntimeTemplate {
has_dynamic_chunks,
has_hmr,
umd,
umd_export,
is_browser: matches!(context.config.platform, crate::config::Platform::Browser),
cjs: context.config.cjs,
chunk_loading_global: serde_json::to_string(&context.config.output.chunk_loading_global)
Expand Down
1 change: 1 addition & 0 deletions crates/mako/src/generate/runtime.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ pub struct AppRuntimeTemplate {
pub has_dynamic_chunks: bool,
pub has_hmr: bool,
pub umd: Option<String>,
pub umd_export: Vec<String>,
pub cjs: bool,
pub pkg_name: Option<String>,
pub chunk_loading_global: String,
Expand Down
2 changes: 1 addition & 1 deletion crates/mako/templates/app_runtime.stpl
Original file line number Diff line number Diff line change
Expand Up @@ -431,7 +431,7 @@ root.makoModuleHotUpdate = runtime._makoModuleHotUpdate;
else if (typeof exports === 'object') exports['<%= umd.clone().unwrap() %>'] = factory();
else root['<%= umd.clone().unwrap() %>'] = factory();
})(typeof self !== 'undefined' ? self : this, function () {
return runtime.exports;
return runtime.exports<% if umd_export.is_empty() { %><% } else { %><%-umd_export.join("")%><% } %>;
});
<% } %>

Expand Down
2 changes: 1 addition & 1 deletion docs/config.md
Original file line number Diff line number Diff line change
Expand Up @@ -820,7 +820,7 @@ e.g.

### umd

- Type: `false | string`
- Type: `false | string | { name: string, export?: string [] }`
- Default: `false`

Whether to output umd format.
Expand Down
2 changes: 1 addition & 1 deletion docs/config.zh-CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -815,7 +815,7 @@ babel-plugin-import 的简化版本,仅支持三个配置项:libraryName,l

### umd

- 类型:`false | string`
- 类型:`false | string | { name: string, export?: string[] }`
- 默认值:`false`

是否输出 umd 格式。
Expand Down
3 changes: 3 additions & 0 deletions e2e/fixtures/config.umd_export/expect.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
const assert = require("assert");

assert(require("./dist/index.js") === "foo", "umd export should work")
1 change: 1 addition & 0 deletions e2e/fixtures/config.umd_export/mako.config.json
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{ "umd": { "name": "foooo", "export": ["default", "x"] } }
1 change: 1 addition & 0 deletions e2e/fixtures/config.umd_export/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export default { x: 'foo'};
2 changes: 1 addition & 1 deletion packages/mako/binding.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -190,7 +190,7 @@ export interface BuildParams {
autoCSSModules?: boolean;
ignoreCSSParserErrors?: boolean;
dynamicImportToRequire?: boolean;
umd?: false | string;
umd?: false | string | { name: string; export?: string[] };
cjs?: boolean;
writeToDisk?: boolean;
transformImport?: {
Expand Down
Loading