From 5b4e068fb0ec671d37d794a8293784eac36a84de Mon Sep 17 00:00:00 2001 From: pshu Date: Thu, 21 Nov 2024 10:32:32 +0800 Subject: [PATCH 01/13] =?UTF-8?q?fix(SSU):=20=F0=9F=90=9B=20in=20case=20ex?= =?UTF-8?q?ternal=20not=20avaible=20to=20all=20=20entries=20(#1698)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * fix(SSU): 🐛 in case external not avaible to all entries * refactor: 🎨 explict ignore the error --- crates/mako/src/plugins/central_ensure.rs | 2 +- crates/mako/src/plugins/ssu.rs | 8 ++++++-- 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/crates/mako/src/plugins/central_ensure.rs b/crates/mako/src/plugins/central_ensure.rs index 2f9d8ed49..b3fcbaaac 100644 --- a/crates/mako/src/plugins/central_ensure.rs +++ b/crates/mako/src/plugins/central_ensure.rs @@ -61,7 +61,7 @@ impl Plugin for CentralChunkEnsure { let map = {ensure_map}; requireModule.updateEnsure2Map = function(newMapping) {{ map = newMapping; - }} + }}; requireModule.ensure2 = function(chunkId){{ let toEnsure = map[chunkId]; if (toEnsure) {{ diff --git a/crates/mako/src/plugins/ssu.rs b/crates/mako/src/plugins/ssu.rs index 9754ea616..83a683c13 100644 --- a/crates/mako/src/plugins/ssu.rs +++ b/crates/mako/src/plugins/ssu.rs @@ -256,7 +256,11 @@ require("{SSU_MOCK_JS_FILE}"); }}catch(e){{}}; let patch = require._su_patch(); console.log(patch); +try{{ {} +}}catch(e){{ +//ignore the error +}} module.export = Promise.all( patch.map((d)=>__mako_require__.ensure(d)) ).then(()=>{{ @@ -566,7 +570,7 @@ requireModule._su_patch = function(){{ cssChunksIdToUrlMap[key] = css_patch[key]; }} return Object.keys(js_patch).sort(); -}} +}}; "#, serde_json::to_string(&cache.js_patch_map).unwrap(), serde_json::to_string(&cache.css_patch_map).unwrap(), @@ -598,7 +602,7 @@ requireModule._su_patch = function(){ cssChunksIdToUrlMap[key] = css_patch[key]; } return ["node_modules"]; -}"# +};"# .to_string()]) } } From d9017fab13b51d5314815e3983dcce5912dde95c Mon Sep 17 00:00:00 2001 From: Jinbao1001 Date: Thu, 21 Nov 2024 18:04:28 +0800 Subject: [PATCH 02/13] fix: devserver response header add cacheControl no-cache (#1692) * fix: add no-cache * feat: add cross origin --- crates/mako/src/dev.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/crates/mako/src/dev.rs b/crates/mako/src/dev.rs index 4f59f2ac0..6d5346508 100644 --- a/crates/mako/src/dev.rs +++ b/crates/mako/src/dev.rs @@ -10,7 +10,7 @@ use anyhow::{self, Result}; use colored::Colorize; use futures::{SinkExt, StreamExt}; use get_if_addrs::get_if_addrs; -use hyper::header::CONTENT_TYPE; +use hyper::header::{ACCESS_CONTROL_ALLOW_ORIGIN, CACHE_CONTROL, CONTENT_TYPE}; use hyper::service::{make_service_fn, service_fn}; use hyper::{Body, Request, Server}; use notify_debouncer_full::new_debouncer; @@ -179,6 +179,8 @@ impl DevServer { return Ok(hyper::Response::builder() .status(hyper::StatusCode::OK) + .header(CACHE_CONTROL, "no-cache") + .header(ACCESS_CONTROL_ALLOW_ORIGIN, "*") .header(CONTENT_TYPE, content_type) .body(hyper::Body::from(res)) .unwrap()); From 0d491c8ff8c877954dd790629cea09531201259a Mon Sep 17 00:00:00 2001 From: Jinbao1001 Date: Mon, 25 Nov 2024 10:08:23 +0800 Subject: [PATCH 03/13] fix: resonse header add cors and no_cache for all branch (#1699) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * fix: judge devServer instead of writeToDisk * fix: add branch header * refactor: 🎨 static file with 0 ages --------- Co-authored-by: pshu --- crates/mako/src/dev.rs | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/crates/mako/src/dev.rs b/crates/mako/src/dev.rs index 6d5346508..0dae20352 100644 --- a/crates/mako/src/dev.rs +++ b/crates/mako/src/dev.rs @@ -72,8 +72,12 @@ impl DevServer { Ok::<_, hyper::Error>(service_fn(move |req| { let context = context.clone(); let txws = txws.clone(); - let staticfile = - hyper_staticfile::Static::new(context.config.output.path.clone()); + let staticfile = { + let mut sf = + hyper_staticfile::Static::new(context.config.output.path.clone()); + sf.cache_headers(Some(0)); + sf + }; async move { Self::handle_requests(req, context, staticfile, txws).await } })) } @@ -196,6 +200,8 @@ impl DevServer { Ok(hyper::Response::builder() .status(hyper::StatusCode::OK) .header(CONTENT_TYPE, content_type) + .header(CACHE_CONTROL, "no-cache") + .header(ACCESS_CONTROL_ALLOW_ORIGIN, "*") .body(hyper::Body::from(bytes)) .unwrap()) }); From d43cc580783a00577957e012e0fc167a4cb225c3 Mon Sep 17 00:00:00 2001 From: pshu Date: Mon, 25 Nov 2024 10:47:58 +0800 Subject: [PATCH 04/13] release: @umijs/mako@0.9.7 --- packages/bundler-mako/package.json | 2 +- packages/mako/npm/darwin-arm64/package.json | 2 +- packages/mako/npm/darwin-x64/package.json | 2 +- packages/mako/npm/linux-arm64-gnu/package.json | 2 +- .../mako/npm/linux-arm64-musl/package.json | 2 +- packages/mako/npm/linux-x64-gnu/package.json | 2 +- packages/mako/npm/linux-x64-musl/package.json | 2 +- packages/mako/npm/win32-ia32-msvc/package.json | 2 +- packages/mako/npm/win32-x64-msvc/package.json | 2 +- packages/mako/package.json | 18 +++++++++--------- 10 files changed, 18 insertions(+), 18 deletions(-) diff --git a/packages/bundler-mako/package.json b/packages/bundler-mako/package.json index d93d83dfb..2c7df8ce1 100644 --- a/packages/bundler-mako/package.json +++ b/packages/bundler-mako/package.json @@ -3,7 +3,7 @@ "version": "0.9.6", "dependencies": { "@umijs/bundler-utils": "^4.0.81", - "@umijs/mako": "0.9.6", + "@umijs/mako": "0.9.7", "chalk": "^4.1.2", "compression": "^1.7.4", "connect-history-api-fallback": "^2.0.0", diff --git a/packages/mako/npm/darwin-arm64/package.json b/packages/mako/npm/darwin-arm64/package.json index 1308d094d..5421dee92 100644 --- a/packages/mako/npm/darwin-arm64/package.json +++ b/packages/mako/npm/darwin-arm64/package.json @@ -1,6 +1,6 @@ { "name": "@umijs/mako-darwin-arm64", - "version": "0.9.6", + "version": "0.9.7", "os": [ "darwin" ], diff --git a/packages/mako/npm/darwin-x64/package.json b/packages/mako/npm/darwin-x64/package.json index 263e8e769..6465a702b 100644 --- a/packages/mako/npm/darwin-x64/package.json +++ b/packages/mako/npm/darwin-x64/package.json @@ -1,6 +1,6 @@ { "name": "@umijs/mako-darwin-x64", - "version": "0.9.6", + "version": "0.9.7", "os": [ "darwin" ], diff --git a/packages/mako/npm/linux-arm64-gnu/package.json b/packages/mako/npm/linux-arm64-gnu/package.json index b851a7f3a..89f4d4d18 100644 --- a/packages/mako/npm/linux-arm64-gnu/package.json +++ b/packages/mako/npm/linux-arm64-gnu/package.json @@ -1,6 +1,6 @@ { "name": "@umijs/mako-linux-arm64-gnu", - "version": "0.9.6", + "version": "0.9.7", "os": [ "linux" ], diff --git a/packages/mako/npm/linux-arm64-musl/package.json b/packages/mako/npm/linux-arm64-musl/package.json index 6c669ecd8..e2ee13821 100644 --- a/packages/mako/npm/linux-arm64-musl/package.json +++ b/packages/mako/npm/linux-arm64-musl/package.json @@ -1,6 +1,6 @@ { "name": "@umijs/mako-linux-arm64-musl", - "version": "0.9.6", + "version": "0.9.7", "os": [ "linux" ], diff --git a/packages/mako/npm/linux-x64-gnu/package.json b/packages/mako/npm/linux-x64-gnu/package.json index b64f01323..10817a09f 100644 --- a/packages/mako/npm/linux-x64-gnu/package.json +++ b/packages/mako/npm/linux-x64-gnu/package.json @@ -1,6 +1,6 @@ { "name": "@umijs/mako-linux-x64-gnu", - "version": "0.9.6", + "version": "0.9.7", "os": [ "linux" ], diff --git a/packages/mako/npm/linux-x64-musl/package.json b/packages/mako/npm/linux-x64-musl/package.json index a78d34f05..2429cda18 100644 --- a/packages/mako/npm/linux-x64-musl/package.json +++ b/packages/mako/npm/linux-x64-musl/package.json @@ -1,6 +1,6 @@ { "name": "@umijs/mako-linux-x64-musl", - "version": "0.9.6", + "version": "0.9.7", "os": [ "linux" ], diff --git a/packages/mako/npm/win32-ia32-msvc/package.json b/packages/mako/npm/win32-ia32-msvc/package.json index 874925e21..a5d5be738 100644 --- a/packages/mako/npm/win32-ia32-msvc/package.json +++ b/packages/mako/npm/win32-ia32-msvc/package.json @@ -1,6 +1,6 @@ { "name": "@umijs/mako-win32-ia32-msvc", - "version": "0.9.6", + "version": "0.9.7", "os": [ "win32" ], diff --git a/packages/mako/npm/win32-x64-msvc/package.json b/packages/mako/npm/win32-x64-msvc/package.json index dc2e289da..837ff4dbc 100644 --- a/packages/mako/npm/win32-x64-msvc/package.json +++ b/packages/mako/npm/win32-x64-msvc/package.json @@ -1,6 +1,6 @@ { "name": "@umijs/mako-win32-x64-msvc", - "version": "0.9.6", + "version": "0.9.7", "os": [ "win32" ], diff --git a/packages/mako/package.json b/packages/mako/package.json index 7ec1f7a8e..bc6b2f7ed 100644 --- a/packages/mako/package.json +++ b/packages/mako/package.json @@ -1,6 +1,6 @@ { "name": "@umijs/mako", - "version": "0.9.6", + "version": "0.9.7", "main": "dist/index.js", "types": "dist/index.d.ts", "bin": { @@ -75,14 +75,14 @@ "src:build": "father build" }, "optionalDependencies": { - "@umijs/mako-darwin-arm64": "0.9.6", - "@umijs/mako-linux-arm64-gnu": "0.9.6", - "@umijs/mako-linux-arm64-musl": "0.9.6", - "@umijs/mako-win32-ia32-msvc": "0.9.6", - "@umijs/mako-darwin-x64": "0.9.6", - "@umijs/mako-win32-x64-msvc": "0.9.6", - "@umijs/mako-linux-x64-gnu": "0.9.6", - "@umijs/mako-linux-x64-musl": "0.9.6" + "@umijs/mako-darwin-arm64": "0.9.7", + "@umijs/mako-linux-arm64-gnu": "0.9.7", + "@umijs/mako-linux-arm64-musl": "0.9.7", + "@umijs/mako-win32-ia32-msvc": "0.9.7", + "@umijs/mako-darwin-x64": "0.9.7", + "@umijs/mako-win32-x64-msvc": "0.9.7", + "@umijs/mako-linux-x64-gnu": "0.9.7", + "@umijs/mako-linux-x64-musl": "0.9.7" }, "repository": "git@github.com:umijs/mako.git" } \ No newline at end of file From e3c3b20575a840ff1761ce10bc7c266a2db21bcc Mon Sep 17 00:00:00 2001 From: pshu Date: Mon, 25 Nov 2024 10:48:46 +0800 Subject: [PATCH 05/13] chore: bundler-mako@0.9.7 --- packages/bundler-mako/package.json | 2 +- pnpm-lock.yaml | 73 ++++++++++++++++-------------- 2 files changed, 40 insertions(+), 35 deletions(-) diff --git a/packages/bundler-mako/package.json b/packages/bundler-mako/package.json index 2c7df8ce1..c422914dd 100644 --- a/packages/bundler-mako/package.json +++ b/packages/bundler-mako/package.json @@ -1,6 +1,6 @@ { "name": "@umijs/bundler-mako", - "version": "0.9.6", + "version": "0.9.7", "dependencies": { "@umijs/bundler-utils": "^4.0.81", "@umijs/mako": "0.9.7", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 4c616c68c..425aa5c9b 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -241,6 +241,12 @@ importers: specifier: 18.2.0 version: 18.2.0(react@18.2.0) + examples/ppp-ssu-case-1: + dependencies: + lodash-es: + specifier: ^4.17.21 + version: 4.17.21 + examples/react: dependencies: react: @@ -436,7 +442,7 @@ importers: specifier: ^4.0.81 version: 4.1.6 '@umijs/mako': - specifier: 0.9.6 + specifier: 0.9.7 version: link:../mako chalk: specifier: ^4.1.2 @@ -537,29 +543,29 @@ importers: version: 21.1.1 optionalDependencies: '@umijs/mako-darwin-arm64': - specifier: 0.9.6 - version: 0.9.6 + specifier: 0.9.7 + version: 0.9.7 '@umijs/mako-darwin-x64': - specifier: 0.9.6 - version: 0.9.6 + specifier: 0.9.7 + version: 0.9.7 '@umijs/mako-linux-arm64-gnu': - specifier: 0.9.6 - version: 0.9.6 + specifier: 0.9.7 + version: 0.9.7 '@umijs/mako-linux-arm64-musl': - specifier: 0.9.6 - version: 0.9.6 + specifier: 0.9.7 + version: 0.9.7 '@umijs/mako-linux-x64-gnu': - specifier: 0.9.6 - version: 0.9.6 + specifier: 0.9.7 + version: 0.9.7 '@umijs/mako-linux-x64-musl': - specifier: 0.9.6 - version: 0.9.6 + specifier: 0.9.7 + version: 0.9.7 '@umijs/mako-win32-ia32-msvc': - specifier: 0.9.6 - version: 0.9.6 + specifier: 0.9.7 + version: 0.9.7 '@umijs/mako-win32-x64-msvc': - specifier: 0.9.6 - version: 0.9.6 + specifier: 0.9.7 + version: 0.9.7 devDependencies: '@napi-rs/cli': specifier: ^2.18.0 @@ -6512,8 +6518,8 @@ packages: dev: true optional: true - /@umijs/mako-darwin-arm64@0.9.6: - resolution: {integrity: sha512-AvYzWOornkq4LUio4RSMWmWwjceyH1CTNzyia85RYYLnjT+JaJZsJVF2R9CyFSDaaM80uoQLihCB2u/Tl87BQg==} + /@umijs/mako-darwin-arm64@0.9.7: + resolution: {integrity: sha512-mOmhSuR0v0FpJ6jW2EDyvUbevQmrd54ly8vLO+L/Rv83GiOzlu7V97GwpW1kQUrNiN7jWiFy6inDhF2lQ1apnw==} engines: {node: '>= 10'} cpu: [arm64] os: [darwin] @@ -6530,8 +6536,8 @@ packages: dev: true optional: true - /@umijs/mako-darwin-x64@0.9.6: - resolution: {integrity: sha512-t/PHtUFdt8sUcoTQ5VxUV6RnA/aOsvYXe250CnmZQwM7EqNStuQQ1FyhoGQj1XV94WRGSmKb36ISjO4svaLP1Q==} + /@umijs/mako-darwin-x64@0.9.7: + resolution: {integrity: sha512-Wf+oHQv/93M5/yzdkBK5nZBzuSde1lZB1kICVToriTW9UV7BnC8i0EFtUmerRBqLcE8cUX9jnRBoYZwO1jaotA==} engines: {node: '>= 10'} cpu: [x64] os: [darwin] @@ -6539,8 +6545,8 @@ packages: dev: false optional: true - /@umijs/mako-linux-arm64-gnu@0.9.6: - resolution: {integrity: sha512-9eL3o3uVSEhUbkdsesv1rBjqtP3XfKrwsfgLsaPvJqgbORBeWOsppmWjNotmJsbxKaQIZBJeb3ZxxrD9iYpW/g==} + /@umijs/mako-linux-arm64-gnu@0.9.7: + resolution: {integrity: sha512-ZD2s5B38Gp8SIJENJ99PWhv/8+LbQiEAZTuT3fIdDOWvTvism3kCM82QwPsNOambVtCVHrbM5cAWLp8wfFcUoA==} engines: {node: '>= 10'} cpu: [arm64] os: [linux] @@ -6548,8 +6554,8 @@ packages: dev: false optional: true - /@umijs/mako-linux-arm64-musl@0.9.6: - resolution: {integrity: sha512-7ozS0sK5wyWqge0I8vSNF1oO2OssXMMoHgj9u5i+7dHY/ayyBx+xB/PbnVYofMJOmZUKjEnFezK62llUaeF/4w==} + /@umijs/mako-linux-arm64-musl@0.9.7: + resolution: {integrity: sha512-OJCdq+zE/5QZwKYZH0zIB7fTckxUvCnFWgqq/oWY965A4P9JRDxIDcEp3nM1b18rUpGN799JVbbO1LRAco0Row==} engines: {node: '>= 10'} cpu: [arm64] os: [linux] @@ -6566,8 +6572,8 @@ packages: dev: true optional: true - /@umijs/mako-linux-x64-gnu@0.9.6: - resolution: {integrity: sha512-sMfgQcurFOOXGtV/+4vJQu+iAmJ4RDb6J+3m464cKvnBDNM9I+Ye7UGhO+krJZbPN2EheliEN5AWcvKILQeEeA==} + /@umijs/mako-linux-x64-gnu@0.9.7: + resolution: {integrity: sha512-RNgoO3Ux3fJ48W62G6ibktnQvdgTN0Nrj03iUJ4WWfbt2LuJwGfFw25aHVV53ylHSN+gRXe5PQJ7xyDXmaD/kA==} engines: {node: '>= 10'} cpu: [x64] os: [linux] @@ -6584,8 +6590,8 @@ packages: dev: true optional: true - /@umijs/mako-linux-x64-musl@0.9.6: - resolution: {integrity: sha512-uDfMGIbH2mq1HoQOeUmQqqBf4emcG3y0s9dKQu3P9sW93EWK35qUHBfuhYeRP7d6/ljfNhB35Bqe6SHU/KV4cw==} + /@umijs/mako-linux-x64-musl@0.9.7: + resolution: {integrity: sha512-bthSiiHZc5sNNLLK/ivSZ0KpUXGKR+eZwcKYa54L6AOy90GEbuY668lSJFP1+B20FC6pen0CNxko8OR6dgxB2A==} engines: {node: '>= 10'} cpu: [x64] os: [linux] @@ -6593,8 +6599,8 @@ packages: dev: false optional: true - /@umijs/mako-win32-ia32-msvc@0.9.6: - resolution: {integrity: sha512-h7nRPSD77sQAFFd5IyGa8+qctrbU4/QHsfPXZeikYDM9TvqkK7Z61Aixcm5YgAFmyKgtftHJZc7BEOHMoYu7QQ==} + /@umijs/mako-win32-ia32-msvc@0.9.7: + resolution: {integrity: sha512-0S2HJNcMkDidK3QU2BgYFzXUi1phRDOyiT+bHcYyVJR4vARSb9GwrgAkooNaUxy3vn1x4dmNw/JL/4jxxtQ6jw==} engines: {node: '>= 10'} cpu: [ia32] os: [win32] @@ -6602,8 +6608,8 @@ packages: dev: false optional: true - /@umijs/mako-win32-x64-msvc@0.9.6: - resolution: {integrity: sha512-xtJmfj8pdABLoosHNyzgCILhgrXn/VE8YsBUiKa88w4OpnZ0KHwMM8AhYZO06Fy88u+lOk7vVUB7/GuyAxY8JA==} + /@umijs/mako-win32-x64-msvc@0.9.7: + resolution: {integrity: sha512-g6ocRGSg2hLdl8gmqF3QgC7tFwurOvjY77HJzjJ0DJx3w43UwgmAkn+S6LrPwXqwwL53dldl8x1arkdcfxJEQA==} engines: {node: '>= 10'} cpu: [x64] os: [win32] @@ -12238,7 +12244,6 @@ packages: /lodash-es@4.17.21: resolution: {integrity: sha512-mKnC+QJ9pWVzv+C4/U3rRsHapFfHvQFoFB92e52xeyGMcX6/OlIl78je1u8vePzYZSkkogMPJ2yjxxsb89cxyw==} - dev: true /lodash.debounce@4.0.8: resolution: {integrity: sha512-FT1yDzDYEoYWhnSGnpE/4Kj1fLZkDFyqRb7fNt6FdYOSxlUWAtp42Eh6Wb0rGIv/m9Bgo7x4GhQbm5Ys4SG5ow==} From cb5bc5ff6386fb327dbc51a81a4116f2964f3c64 Mon Sep 17 00:00:00 2001 From: pshu Date: Mon, 25 Nov 2024 11:09:10 +0800 Subject: [PATCH 06/13] =?UTF-8?q?docs:=20=F0=9F=93=9D=20=20update=20change?= =?UTF-8?q?log=20for=200.9.7?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- CHANGELOG.md | 7 +++++++ CHANGELOG_zh-CN.md | 7 +++++++ 2 files changed, 14 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index a8e4d625f..4044b389e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,10 @@ +## 0.9.7 + +`2024-11-25` + +- fix: devserver response header add cacheControl no-cache by [@Jinbao1001](https://github.com/Jinbao1001) in [#1692](https://github.com/umijs/mako/pull/1692) [#1699](https://github.com/umijs/mako/pull/1699) +- fix(ssu): in case external not available to all entries by [@stormslowly](https://github.com/stormslowly) in [#1698](https://github.com/umijs/mako/pull/1698) + ## 0.9.6 `2024-11-14` diff --git a/CHANGELOG_zh-CN.md b/CHANGELOG_zh-CN.md index cadf4f5ff..1e97608e9 100644 --- a/CHANGELOG_zh-CN.md +++ b/CHANGELOG_zh-CN.md @@ -1,3 +1,10 @@ +## 0.9.7 + +`2024-11-25` + +- 修复: 开发服务器未设置缓存头问题 by [@Jinbao1001](https://github.com/Jinbao1001) in [#1692](https://github.com/umijs/mako/pull/1692) [#1699](https://github.com/umijs/mako/pull/1699) +- 修复: SSU 补偿的 external 代码可能出错的情况 [@stormslowly](https://github.com/stormslowly) in [#1698](https://github.com/umijs/mako/pull/1698) + ## 0.9.6 `2024-11-14` From b6f638dd9d5833bf67af828a5f2dfa218a860908 Mon Sep 17 00:00:00 2001 From: pshu Date: Wed, 27 Nov 2024 17:46:10 +0800 Subject: [PATCH 07/13] =?UTF-8?q?chore:=20=E2=9C=8F=EF=B8=8F=20remove=20so?= =?UTF-8?q?me=20if=20(#1706)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../src/plugins/duplicate_package_checker.rs | 53 ++++++++++--------- crates/mako/src/visitors/async_module.rs | 2 +- 2 files changed, 30 insertions(+), 25 deletions(-) diff --git a/crates/mako/src/plugins/duplicate_package_checker.rs b/crates/mako/src/plugins/duplicate_package_checker.rs index ba6b0760d..297e74427 100644 --- a/crates/mako/src/plugins/duplicate_package_checker.rs +++ b/crates/mako/src/plugins/duplicate_package_checker.rs @@ -5,6 +5,7 @@ use std::sync::{Arc, RwLock}; use semver::Version; use crate::compiler::Context; +use crate::module::Module; use crate::module_graph::ModuleGraph; use crate::plugin::Plugin; use crate::resolve::ResolverResource; @@ -46,6 +47,30 @@ fn clean_path_relative_to_context(module_path: &Path, context: &Path) -> PathBuf } } +fn extract_package_info(module: &Module) -> Option { + module + .info + .as_ref() + .and_then(|info| info.resolved_resource.as_ref()) + .and_then(|resolver_resource| { + if let ResolverResource::Resolved(resource) = resolver_resource { + let package_json = resource.0.package_json()?; + let name = package_json.name.clone()?; + let raw_json = package_json.raw_json(); + let version = raw_json.as_object()?.get("version")?; + let version = semver::Version::parse(version.as_str().unwrap()).ok()?; + + Some(PackageInfo { + name, + version, + path: package_json.path.clone(), + }) + } else { + None + } + }) +} + impl DuplicatePackageCheckerPlugin { pub fn new() -> Self { Self::default() @@ -92,30 +117,10 @@ impl DuplicatePackageCheckerPlugin { .read() .unwrap() .modules() - .iter() - .for_each(|module| { - if let Some(ResolverResource::Resolved(resource)) = module - .info - .as_ref() - .and_then(|info| info.resolved_resource.as_ref()) - { - if let Some(package_json) = resource.0.package_json() { - let raw_json = package_json.raw_json(); - if let Some(name) = package_json.name.clone() { - if let Some(version) = raw_json.as_object().unwrap().get("version") { - let version = semver::Version::parse(version.as_str().unwrap()); - if let Ok(version) = version { - let package_info = PackageInfo { - name, - version, - path: package_json.path.clone(), - }; - packages.push(package_info); - } - } - } - } - } + .into_iter() + .filter_map(extract_package_info) + .for_each(|package_info| { + packages.push(package_info); }); Self::find_duplicates(packages) diff --git a/crates/mako/src/visitors/async_module.rs b/crates/mako/src/visitors/async_module.rs index 870085d09..e5cf0ba4b 100644 --- a/crates/mako/src/visitors/async_module.rs +++ b/crates/mako/src/visitors/async_module.rs @@ -218,7 +218,7 @@ pub fn mark_async( .filter_map(|m| { m.info .as_ref() - .and_then(|i| if i.is_async { Some(m.id.clone()) } else { None }) + .and_then(|i| i.is_async.then(|| m.id.clone())) }) .collect::>(); let mut visited = HashSet::new(); From c14097255a00b50eb6f999d43b3499fc626be4d5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?chencheng=20=28=E4=BA=91=E8=B0=A6=29?= Date: Fri, 29 Nov 2024 14:46:50 +0800 Subject: [PATCH 08/13] fix: optimization.concatenateModules dts lost (#1708) --- crates/binding/src/lib.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/crates/binding/src/lib.rs b/crates/binding/src/lib.rs index 39c039d13..703c19978 100644 --- a/crates/binding/src/lib.rs +++ b/crates/binding/src/lib.rs @@ -146,6 +146,7 @@ pub struct BuildParams { }; optimization?: false | { skipModules?: boolean; + concatenateModules?: boolean; }; react?: { runtime?: "automatic" | "classic"; From 89d7c53bd9290a316704a0b40eaefcb7cd9c2d84 Mon Sep 17 00:00:00 2001 From: pshu Date: Fri, 29 Nov 2024 17:05:49 +0800 Subject: [PATCH 09/13] =?UTF-8?q?refactor:=20=F0=9F=94=A5=20enter=20ensure?= =?UTF-8?q?=20=E4=BD=BF=E7=94=A8=20chunk=20sync=20dep=20=E5=87=8F=E5=B0=91?= =?UTF-8?q?=E9=A6=96=E5=B1=8F=20chunk=20=E6=95=B0=E9=87=8F=20(#1707)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- crates/mako/src/plugins/central_ensure.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/crates/mako/src/plugins/central_ensure.rs b/crates/mako/src/plugins/central_ensure.rs index b3fcbaaac..6c2c31f5e 100644 --- a/crates/mako/src/plugins/central_ensure.rs +++ b/crates/mako/src/plugins/central_ensure.rs @@ -1,4 +1,5 @@ use std::collections::BTreeMap; +use std::iter::once; use std::sync::Arc; use anyhow::anyhow; @@ -32,8 +33,9 @@ pub fn module_ensure_map(context: &Arc) -> anyhow::Result>(); From 569ef8d33494ee78f868d656f0b5a13c3c4a244c Mon Sep 17 00:00:00 2001 From: pshu Date: Tue, 3 Dec 2024 09:32:01 +0800 Subject: [PATCH 10/13] =?UTF-8?q?fix:=20=F0=9F=90=9B=20typing=20of=20stats?= =?UTF-8?q?=20(#1712)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- crates/binding/src/lib.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/crates/binding/src/lib.rs b/crates/binding/src/lib.rs index 703c19978..a99a9ead8 100644 --- a/crates/binding/src/lib.rs +++ b/crates/binding/src/lib.rs @@ -119,7 +119,9 @@ pub struct BuildParams { selectorDoubleList?: string[]; mediaQuery?: boolean; }; - stats?: boolean; + stats?: false | { + modules?: boolean; + }; hash?: boolean; autoCSSModules?: boolean; ignoreCSSParserErrors?: boolean; From 190121297d8b4d45eff30002573e62cac68dcc7c Mon Sep 17 00:00:00 2001 From: pshu Date: Wed, 4 Dec 2024 14:29:31 +0800 Subject: [PATCH 11/13] =?UTF-8?q?fix:=20=F0=9F=90=9B=20detect=20circular?= =?UTF-8?q?=20deps=20output=20file=20content=20(#1715)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- crates/mako/src/plugins/detect_circular_dependence.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/mako/src/plugins/detect_circular_dependence.rs b/crates/mako/src/plugins/detect_circular_dependence.rs index e22b7e072..87382f615 100644 --- a/crates/mako/src/plugins/detect_circular_dependence.rs +++ b/crates/mako/src/plugins/detect_circular_dependence.rs @@ -68,7 +68,7 @@ impl Plugin for LoopDetector { if detect_loop.graphviz { let dot_content = loop_lines.join("\n"); - let dot = format!(r#"digraph Loop {{\n{}\n}}"#, dot_content); + let dot = format!("digraph Loop {{\n{}\n}}\n", dot_content); std::fs::write(context.root.join("_mako_loop_detector.dot"), dot)?; } } From a89b63d93b9e76ea2c08824f501a8aad4279bd5c Mon Sep 17 00:00:00 2001 From: pshu Date: Wed, 4 Dec 2024 14:38:29 +0800 Subject: [PATCH 12/13] chore: update @umijs/mako typings --- packages/mako/binding.d.ts | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/packages/mako/binding.d.ts b/packages/mako/binding.d.ts index fa889880d..45f86798a 100644 --- a/packages/mako/binding.d.ts +++ b/packages/mako/binding.d.ts @@ -181,7 +181,11 @@ export interface BuildParams { selectorDoubleList?: string[]; mediaQuery?: boolean; }; - stats?: boolean; + stats?: + | false + | { + modules?: boolean; + }; hash?: boolean; autoCSSModules?: boolean; ignoreCSSParserErrors?: boolean; @@ -232,6 +236,7 @@ export interface BuildParams { | false | { skipModules?: boolean; + concatenateModules?: boolean; }; react?: { runtime?: 'automatic' | 'classic'; From ea532ba31d031d6530bf016160656059301b9bf5 Mon Sep 17 00:00:00 2001 From: Jinbao1001 Date: Thu, 5 Dec 2024 15:20:32 +0800 Subject: [PATCH 13/13] feat: ensure esm imports exists when mode is production (#1709) * feat: ensure esm imports exists when mode is production --- crates/mako/src/ast/utils.rs | 21 +++ crates/mako/src/build.rs | 5 + crates/mako/src/compiler.rs | 6 +- crates/mako/src/config/experimental.rs | 1 + .../mako/src/config/mako.config.default.json | 3 +- crates/mako/src/module.rs | 9 ++ crates/mako/src/plugins.rs | 1 + crates/mako/src/plugins/imports_checker.rs | 122 ++++++++++++++++++ .../imports_checker/collect_exports.rs | 68 ++++++++++ .../imports_checker/collect_imports.rs | 67 ++++++++++ .../mako/src/plugins/tree_shaking/module.rs | 22 +--- crates/mako/src/plugins/tree_shaking/shake.rs | 4 +- .../tree_shaking/shake/find_export_source.rs | 7 +- .../tree_shaking/shake/module_concatenate.rs | 4 +- packages/mako/src/binding.d.ts | 20 +++ 15 files changed, 333 insertions(+), 27 deletions(-) create mode 100644 crates/mako/src/plugins/imports_checker.rs create mode 100644 crates/mako/src/plugins/imports_checker/collect_exports.rs create mode 100644 crates/mako/src/plugins/imports_checker/collect_imports.rs diff --git a/crates/mako/src/ast/utils.rs b/crates/mako/src/ast/utils.rs index 2ef8ba3be..496e8f73e 100644 --- a/crates/mako/src/ast/utils.rs +++ b/crates/mako/src/ast/utils.rs @@ -4,6 +4,8 @@ use swc_core::ecma::ast::{ MetaPropExpr, MetaPropKind, Module, ModuleItem, }; +use crate::module::{ModuleAst, ModuleSystem}; + pub fn is_remote_or_data(url: &str) -> bool { let lower_url = url.to_lowercase(); // ref: @@ -148,3 +150,22 @@ pub fn require_ensure(source: String) -> Expr { }], ) } + +pub fn get_module_system(ast: &ModuleAst) -> ModuleSystem { + match ast { + ModuleAst::Script(module) => { + let is_esm = module + .ast + .body + .iter() + .any(|s| matches!(s, ModuleItem::ModuleDecl(_))); + if is_esm { + ModuleSystem::ESModule + } else { + ModuleSystem::CommonJS + } + } + crate::module::ModuleAst::Css(_) => ModuleSystem::Custom, + crate::module::ModuleAst::None => ModuleSystem::Custom, + } +} diff --git a/crates/mako/src/build.rs b/crates/mako/src/build.rs index b1af48f53..7c66dd0e7 100644 --- a/crates/mako/src/build.rs +++ b/crates/mako/src/build.rs @@ -13,6 +13,7 @@ use colored::Colorize; use thiserror::Error; use crate::ast::file::{Content, File, JsContent}; +use crate::ast::utils::get_module_system; use crate::compiler::{Compiler, Context}; use crate::generate::chunk_pot::util::hash_hashmap; use crate::module::{Module, ModuleAst, ModuleId, ModuleInfo}; @@ -183,6 +184,7 @@ __mako_require__.loadScript('{}', (e) => e.type === 'load' ? resolve() : reject( let raw = file.get_content_raw(); let info = ModuleInfo { file, + module_system: get_module_system(&ast), ast, external: Some(external_name), is_async, @@ -207,6 +209,7 @@ __mako_require__.loadScript('{}', (e) => e.type === 'load' ? resolve() : reject( let raw = file.get_content_raw(); let info = ModuleInfo { file, + module_system: get_module_system(&ast), ast, raw, ..Default::default() @@ -232,6 +235,7 @@ __mako_require__.loadScript('{}', (e) => e.type === 'load' ? resolve() : reject( ModuleInfo { file, + module_system: get_module_system(&ast), ast, is_ignored: true, ..Default::default() @@ -312,6 +316,7 @@ __mako_require__.loadScript('{}', (e) => e.type === 'load' ? resolve() : reject( let info = ModuleInfo { file, deps, + module_system: get_module_system(&ast), ast, resolved_resource: parent_resource, source_map_chain, diff --git a/crates/mako/src/compiler.rs b/crates/mako/src/compiler.rs index fc124a87e..b4be7457b 100644 --- a/crates/mako/src/compiler.rs +++ b/crates/mako/src/compiler.rs @@ -15,7 +15,7 @@ use tracing::debug; use crate::ast::comments::Comments; use crate::ast::file::win_path; -use crate::config::{Config, ModuleIdStrategy, OutputMode}; +use crate::config::{Config, Mode, ModuleIdStrategy, OutputMode}; use crate::generate::chunk_graph::ChunkGraph; use crate::generate::optimize_chunk::OptimizeChunksInfo; use crate::module_graph::ModuleGraph; @@ -258,6 +258,10 @@ impl Compiler { let mut config = config; + if config.mode == Mode::Production && config.experimental.imports_checker { + plugins.push(Arc::new(plugins::imports_checker::ImportsChecker {})); + } + if let Some(progress) = &config.progress { plugins.push(Arc::new(plugins::progress::ProgressPlugin::new( plugins::progress::ProgressPluginOptions { diff --git a/crates/mako/src/config/experimental.rs b/crates/mako/src/config/experimental.rs index 1c86ec1cc..f0987cfdd 100644 --- a/crates/mako/src/config/experimental.rs +++ b/crates/mako/src/config/experimental.rs @@ -13,6 +13,7 @@ pub struct ExperimentalConfig { #[serde(deserialize_with = "deserialize_detect_loop")] pub detect_circular_dependence: Option, pub central_ensure: bool, + pub imports_checker: bool, } #[derive(Deserialize, Serialize, Debug)] diff --git a/crates/mako/src/config/mako.config.default.json b/crates/mako/src/config/mako.config.default.json index be971fdbb..dc0d0ef45 100644 --- a/crates/mako/src/config/mako.config.default.json +++ b/crates/mako/src/config/mako.config.default.json @@ -73,7 +73,8 @@ "ignores": ["node_modules"], "graphviz": false }, - "centralEnsure": true + "centralEnsure": true, + "importsChecker": false }, "useDefineForClassFields": true, "emitDecoratorMetadata": false, diff --git a/crates/mako/src/module.rs b/crates/mako/src/module.rs index 3122ea00f..e23aa9b2c 100644 --- a/crates/mako/src/module.rs +++ b/crates/mako/src/module.rs @@ -33,6 +33,13 @@ pub struct Dependency { pub span: Option, } +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum ModuleSystem { + CommonJS, + ESModule, + Custom, +} + bitflags! { #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Default)] pub struct ResolveTypeFlags: u16 { @@ -192,11 +199,13 @@ pub struct ModuleInfo { pub resolved_resource: Option, /// The transformed source map chain of this module pub source_map_chain: Vec>, + pub module_system: ModuleSystem, } impl Default for ModuleInfo { fn default() -> Self { Self { + module_system: ModuleSystem::CommonJS, ast: ModuleAst::None, file: Default::default(), deps: Default::default(), diff --git a/crates/mako/src/plugins.rs b/crates/mako/src/plugins.rs index b2c545d58..53dc5f267 100644 --- a/crates/mako/src/plugins.rs +++ b/crates/mako/src/plugins.rs @@ -10,6 +10,7 @@ pub mod graphviz; pub mod hmr_runtime; pub mod ignore; pub mod import; +pub mod imports_checker; pub mod invalid_webpack_syntax; pub mod manifest; pub mod minifish; diff --git a/crates/mako/src/plugins/imports_checker.rs b/crates/mako/src/plugins/imports_checker.rs new file mode 100644 index 000000000..9db76193a --- /dev/null +++ b/crates/mako/src/plugins/imports_checker.rs @@ -0,0 +1,122 @@ +mod collect_exports; +mod collect_imports; + +use std::collections::{HashMap, HashSet}; +use std::sync::{Arc, RwLockReadGuard}; + +use anyhow::Result; +use collect_exports::CollectExports; +use collect_imports::CollectImports; +use swc_core::ecma::visit::VisitWith; +use tracing::error; + +use crate::compiler::{Compiler, Context}; +use crate::module::{ModuleId, ModuleSystem}; +use crate::module_graph::ModuleGraph; +use crate::plugin::Plugin; + +pub struct ImportsChecker {} + +fn pick_no_export_specifiers_with_imports_info( + module_id: &ModuleId, + module_graph: &RwLockReadGuard, + specifiers: &mut HashSet, +) { + if !specifiers.is_empty() { + let dep_module = module_graph.get_module(module_id).unwrap(); + if let Some(info) = &dep_module.info { + match info.module_system { + ModuleSystem::ESModule => { + let mut exports_star_sources: Vec = vec![]; + let ast = &info.ast.as_script().unwrap().ast; + ast.visit_with(&mut CollectExports { + specifiers, + exports_star_sources: &mut exports_star_sources, + }); + exports_star_sources.into_iter().for_each(|source| { + if let Some(id) = + module_graph.get_dependency_module_by_source(module_id, &source) + { + pick_no_export_specifiers_with_imports_info( + id, + module_graph, + specifiers, + ); + } + }) + } + ModuleSystem::CommonJS | ModuleSystem::Custom => { + specifiers.clear(); + } + } + } + } +} +impl Plugin for ImportsChecker { + fn name(&self) -> &str { + "imports_checker" + } + fn after_build(&self, context: &Arc, _compiler: &Compiler) -> Result<()> { + let mut modules_imports_map: HashMap<&ModuleId, HashMap>> = + HashMap::new(); + + let module_graph = context.module_graph.read().unwrap(); + let modules = module_graph.modules(); + + for m in modules { + if let Some(info) = &m.info { + if !info.file.is_under_node_modules + && matches!(info.module_system, ModuleSystem::ESModule) + { + // 收集 imports + let ast = &info.ast.as_script().unwrap().ast; + let mut import_specifiers: HashMap> = HashMap::new(); + + ast.visit_with(&mut CollectImports { + imports_specifiers_with_source: &mut import_specifiers, + }); + modules_imports_map.insert(&m.id, import_specifiers); + } + } + } + // 收集 exports + modules_imports_map + .iter_mut() + .for_each(|(module_id, import_specifiers)| { + import_specifiers + .iter_mut() + .for_each(|(source, specifiers)| { + if let Some(dep_module_id) = + module_graph.get_dependency_module_by_source(module_id, source) + { + pick_no_export_specifiers_with_imports_info( + dep_module_id, + &module_graph, + specifiers, + ); + } + }) + }); + let mut should_panic = false; + modules_imports_map + .into_iter() + .for_each(|(module_id, import_specifiers)| { + import_specifiers + .into_iter() + .filter(|(_, specifiers)| !specifiers.is_empty()) + .for_each(|(source, specifiers)| { + should_panic = true; + specifiers.iter().for_each(|specifier| { + error!( + "'{}' is undefined: import from '{}' in '{}'", + specifier, source, module_id.id + ); + }) + }); + }); + if should_panic { + panic!("dependency check error!"); + }; + Ok(()) + } +} diff --git a/crates/mako/src/plugins/imports_checker/collect_exports.rs b/crates/mako/src/plugins/imports_checker/collect_exports.rs new file mode 100644 index 000000000..86af24258 --- /dev/null +++ b/crates/mako/src/plugins/imports_checker/collect_exports.rs @@ -0,0 +1,68 @@ +use std::collections::HashSet; + +use swc_core::ecma::ast::*; +use swc_core::ecma::visit::Visit; + +pub struct CollectExports<'a> { + pub specifiers: &'a mut HashSet, + pub exports_star_sources: &'a mut Vec, +} + +impl<'a> Visit for CollectExports<'a> { + fn visit_module_decl(&mut self, node: &ModuleDecl) { + match &node { + // export const a = 1 + ModuleDecl::ExportDecl(ExportDecl { decl, .. }) => match decl { + Decl::Fn(FnDecl { ident, .. }) => { + self.specifiers.remove(&ident.sym.to_string()); + } + Decl::Class(ClassDecl { ident, .. }) => { + self.specifiers.remove(&ident.sym.to_string()); + } + Decl::Var(box VarDecl { decls, .. }) => decls.iter().for_each(|decl| { + if let Pat::Ident(ident) = &decl.name { + self.specifiers.remove(&ident.sym.to_string()); + } + }), + _ => {} + }, + // export default function + ModuleDecl::ExportDefaultDecl(_) => { + self.specifiers.remove(&"default".to_string()); + } + // export default 1 + ModuleDecl::ExportDefaultExpr(_) => { + self.specifiers.remove(&"default".to_string()); + } + // export * from 'b' + ModuleDecl::ExportAll(all) => { + let source = all.src.value.to_string(); + self.exports_star_sources.push(source); + } + // export {a, b} || export {default as c} from 'd' || export a from 'b' + ModuleDecl::ExportNamed(named) => { + named + .specifiers + .iter() + .for_each(|specifier| match &specifier { + ExportSpecifier::Named(named) => { + if let Some(ModuleExportName::Ident(ident)) = &named.exported { + self.specifiers.remove(&ident.sym.to_string()); + } else if let ModuleExportName::Ident(ident) = &named.orig { + self.specifiers.remove(&ident.sym.to_string()); + } + } + ExportSpecifier::Namespace(name_spacing) => { + if let ModuleExportName::Ident(ident) = &name_spacing.name { + self.specifiers.remove(&ident.sym.to_string()); + } + } + ExportSpecifier::Default(default) => { + self.specifiers.remove(&default.exported.sym.to_string()); + } + }) + } + _ => {} + } + } +} diff --git a/crates/mako/src/plugins/imports_checker/collect_imports.rs b/crates/mako/src/plugins/imports_checker/collect_imports.rs new file mode 100644 index 000000000..146c0840a --- /dev/null +++ b/crates/mako/src/plugins/imports_checker/collect_imports.rs @@ -0,0 +1,67 @@ +use std::collections::{HashMap, HashSet}; + +use swc_core::ecma::ast::*; +use swc_core::ecma::visit::Visit; + +pub struct CollectImports<'a> { + pub imports_specifiers_with_source: &'a mut HashMap>, +} + +impl<'a> Visit for CollectImports<'a> { + fn visit_import_decl(&mut self, node: &ImportDecl) { + let source = node.src.value.to_string(); + if self.imports_specifiers_with_source.get(&source).is_none() { + self.imports_specifiers_with_source + .insert(source.clone(), HashSet::new()); + } + + node.specifiers + .iter() + .for_each(|specifier| match specifier { + ImportSpecifier::Named(named) => { + if let Some(ModuleExportName::Ident(ident)) = &named.imported { + self.imports_specifiers_with_source + .get_mut(&source) + .unwrap() + .insert(ident.sym.to_string()); + } else { + self.imports_specifiers_with_source + .get_mut(&source) + .unwrap() + .insert(named.local.sym.to_string()); + } + } + ImportSpecifier::Default(_) => { + self.imports_specifiers_with_source + .get_mut(&source) + .unwrap() + .insert("default".into()); + } + _ => {} + }) + } + + fn visit_named_export(&mut self, node: &NamedExport) { + if let Some(src) = &node.src { + if self + .imports_specifiers_with_source + .get(src.value.as_str()) + .is_none() + { + self.imports_specifiers_with_source + .insert(src.value.to_string(), HashSet::new()); + } + + node.specifiers.iter().for_each(|specifier| { + if let ExportSpecifier::Named(named) = specifier { + if let ModuleExportName::Ident(ident) = &named.orig { + self.imports_specifiers_with_source + .get_mut(src.value.as_str()) + .unwrap() + .insert(ident.sym.to_string()); + } + } + }) + }; + } +} diff --git a/crates/mako/src/plugins/tree_shaking/module.rs b/crates/mako/src/plugins/tree_shaking/module.rs index 50608d790..4c449b9fb 100644 --- a/crates/mako/src/plugins/tree_shaking/module.rs +++ b/crates/mako/src/plugins/tree_shaking/module.rs @@ -4,7 +4,7 @@ use std::fmt::Display; use swc_core::common::SyntaxContext; use swc_core::ecma::ast::{Module as SwcModule, ModuleItem}; -use crate::module::{Module, ModuleId}; +use crate::module::{Module, ModuleId, ModuleSystem}; use crate::plugins::tree_shaking::statement_graph::{ ExportInfo, ExportInfoMatch, ExportSource, ExportSpecifierInfo, ImportInfo, StatementGraph, StatementId, @@ -34,13 +34,6 @@ impl Display for UsedIdent { } } -#[derive(Debug, PartialEq, Eq)] -pub enum ModuleSystem { - CommonJS, - ESModule, - Custom, -} - #[derive(Debug, Clone)] pub enum UsedExports { All, @@ -285,7 +278,7 @@ impl TreeShakeModule { let mut unresolved_ctxt = SyntaxContext::empty(); // 1. generate statement graph - let mut module_system = ModuleSystem::CommonJS; + let module_system = module_info.module_system.clone(); let stmt_graph = match &module_info.ast { crate::module::ModuleAst::Script(module) => { let is_esm = module @@ -294,21 +287,14 @@ impl TreeShakeModule { .iter() .any(|s| matches!(s, ModuleItem::ModuleDecl(_))); if is_esm { - module_system = ModuleSystem::ESModule; unresolved_ctxt = unresolved_ctxt.apply_mark(module.unresolved_mark); StatementGraph::new(&module.ast, unresolved_ctxt) } else { StatementGraph::empty() } } - crate::module::ModuleAst::Css(_) => { - module_system = ModuleSystem::Custom; - StatementGraph::empty() - } - crate::module::ModuleAst::None => { - module_system = ModuleSystem::Custom; - StatementGraph::empty() - } + crate::module::ModuleAst::Css(_) => StatementGraph::empty(), + crate::module::ModuleAst::None => StatementGraph::empty(), }; let used_exports = if module.is_entry { diff --git a/crates/mako/src/plugins/tree_shaking/shake.rs b/crates/mako/src/plugins/tree_shaking/shake.rs index ecefe1886..57d23a545 100644 --- a/crates/mako/src/plugins/tree_shaking/shake.rs +++ b/crates/mako/src/plugins/tree_shaking/shake.rs @@ -15,9 +15,9 @@ use swc_core::ecma::transforms::base::helpers::{Helpers, HELPERS}; use self::skip_module::skip_module_optimize; use crate::compiler::Context; -use crate::module::{ModuleAst, ModuleId, ModuleType, ResolveType}; +use crate::module::{ModuleAst, ModuleId, ModuleSystem, ModuleType, ResolveType}; use crate::module_graph::ModuleGraph; -use crate::plugins::tree_shaking::module::{AllExports, ModuleSystem, TreeShakeModule}; +use crate::plugins::tree_shaking::module::{AllExports, TreeShakeModule}; use crate::plugins::tree_shaking::shake::module_concatenate::optimize_module_graph; use crate::plugins::tree_shaking::statement_graph::{ExportInfo, ExportSpecifierInfo, ImportInfo}; use crate::plugins::tree_shaking::{module, remove_useless_stmts, statement_graph}; diff --git a/crates/mako/src/plugins/tree_shaking/shake/find_export_source.rs b/crates/mako/src/plugins/tree_shaking/shake/find_export_source.rs index 66913341f..030a92e10 100644 --- a/crates/mako/src/plugins/tree_shaking/shake/find_export_source.rs +++ b/crates/mako/src/plugins/tree_shaking/shake/find_export_source.rs @@ -189,6 +189,7 @@ mod tests { use super::TreeShakeModule; use crate::ast::file::{Content, File, JsContent}; use crate::ast::js_ast::JsAst; + use crate::ast::utils::get_module_system; use crate::compiler::Context; use crate::module::{Module, ModuleAst, ModuleInfo}; use crate::plugins::tree_shaking::shake::skip_module::ReExportSource; @@ -465,13 +466,13 @@ mod tests { }), context.clone(), ); - let ast = JsAst::new(&file, context.clone()).unwrap(); - + let ast = ModuleAst::Script(JsAst::new(&file, context.clone()).unwrap()); let mako_module = Module { id: "test.js".into(), is_entry: false, info: Some(ModuleInfo { - ast: ModuleAst::Script(ast), + module_system: get_module_system(&ast), + ast, file, ..Default::default() }), diff --git a/crates/mako/src/plugins/tree_shaking/shake/module_concatenate.rs b/crates/mako/src/plugins/tree_shaking/shake/module_concatenate.rs index d8c67a059..610ecfb56 100644 --- a/crates/mako/src/plugins/tree_shaking/shake/module_concatenate.rs +++ b/crates/mako/src/plugins/tree_shaking/shake/module_concatenate.rs @@ -21,9 +21,9 @@ use self::concatenate_context::EsmDependantFlags; use self::utils::uniq_module_prefix; use crate::ast::js_ast::JsAst; use crate::compiler::Context; -use crate::module::{Dependency, ImportType, ModuleId, ResolveType}; +use crate::module::{Dependency, ImportType, ModuleId, ModuleSystem, ResolveType}; use crate::module_graph::ModuleGraph; -use crate::plugins::tree_shaking::module::{AllExports, ModuleSystem, TreeShakeModule}; +use crate::plugins::tree_shaking::module::{AllExports, TreeShakeModule}; use crate::plugins::tree_shaking::shake::module_concatenate::concatenate_context::{ ConcatenateContext, RuntimeFlags, }; diff --git a/packages/mako/src/binding.d.ts b/packages/mako/src/binding.d.ts index b99643f94..fa889880d 100644 --- a/packages/mako/src/binding.d.ts +++ b/packages/mako/src/binding.d.ts @@ -5,6 +5,7 @@ export interface JsHooks { name?: string; + enforce?: string; load?: ( filePath: string, ) => Promise<{ content: string; type: 'css' | 'js' } | void> | void; @@ -50,13 +51,24 @@ export interface JsHooks { endTime: number; }; }) => void; + writeBundle?: () => Promise; + watchChanges?: ( + id: string, + change: { event: 'create' | 'delete' | 'update' }, + ) => Promise | void; onGenerateFile?: (path: string, content: Buffer) => Promise; buildStart?: () => Promise; + buildEnd?: () => Promise; resolveId?: ( source: string, importer: string, { isEntry: bool }, ) => Promise<{ id: string }>; + transform?: ( + content: { content: string; type: 'css' | 'js' }, + path: string, + ) => Promise<{ content: string; type: 'css' | 'js' } | void> | void; + transformInclude?: (filePath: string) => Promise | bool; } export interface WriteFile { path: string; @@ -66,6 +78,9 @@ export interface LoadResult { content: string; type: string; } +export interface WatchChangesParams { + event: string; +} export interface ResolveIdResult { id: string; external: boolean | null; @@ -73,6 +88,10 @@ export interface ResolveIdResult { export interface ResolveIdParams { isEntry: boolean; } +export interface TransformResult { + content: string; + type: string; +} export interface BuildParams { root: string; config: { @@ -146,6 +165,7 @@ export interface BuildParams { providers?: Record; publicPath?: string; inlineLimit?: number; + inlineExcludesExtensions?: string[]; targets?: Record; platform?: 'node' | 'browser'; hmr?: false | {};