From 13c4107978e12ad8bc5587ece554aeb37e81ce0a Mon Sep 17 00:00:00 2001 From: fi3ework Date: Wed, 11 Dec 2024 16:46:54 +0800 Subject: [PATCH] build: use Rslib to build @rspack/core --- packages/create-rspack/package.json | 2 +- packages/rspack-cli/package.json | 2 +- .../update-hash/hooks.snap.txt | 2 +- .../basic/hooks.snap.txt | 2 +- .../update-hash/hooks.snap.txt | 4 +- .../css/recovery/__snapshots__/web/2.snap.txt | 373 +++++++++--------- packages/rspack/package.json | 6 +- packages/rspack/rslib.config.ts | 155 ++++++++ packages/rspack/src/Compiler.ts | 3 +- packages/rspack/src/index.ts | 2 +- packages/rspack/tsup.config.ts | 3 +- pnpm-lock.yaml | 157 ++------ .../cases/hmr-locals/expected/main.js | 370 ++++++++--------- .../css-extract/cases/hmr/expected/main.js | 370 ++++++++--------- 14 files changed, 719 insertions(+), 732 deletions(-) create mode 100644 packages/rspack/rslib.config.ts diff --git a/packages/create-rspack/package.json b/packages/create-rspack/package.json index 5729a0ac5f3..5f2bf5b6cce 100644 --- a/packages/create-rspack/package.json +++ b/packages/create-rspack/package.json @@ -27,7 +27,7 @@ "create-rstack": "1.0.6" }, "devDependencies": { - "@rslib/core": "0.0.15", + "@rslib/core": "0.1.4", "typescript": "^5.6.3" }, "publishConfig": { diff --git a/packages/rspack-cli/package.json b/packages/rspack-cli/package.json index d6f339903b1..dbef04a63a2 100644 --- a/packages/rspack-cli/package.json +++ b/packages/rspack-cli/package.json @@ -44,7 +44,7 @@ "yargs": "17.6.2" }, "devDependencies": { - "@rslib/core": "0.0.15", + "@rslib/core": "0.1.4", "@rspack/core": "workspace:*", "@types/interpret": "^1.1.3", "@types/rechoir": "^0.6.1", diff --git a/packages/rspack-test-tools/tests/hookCases/compilation#chunkHash/update-hash/hooks.snap.txt b/packages/rspack-test-tools/tests/hookCases/compilation#chunkHash/update-hash/hooks.snap.txt index ab246d92198..6acc18f48ef 100644 --- a/packages/rspack-test-tools/tests/hookCases/compilation#chunkHash/update-hash/hooks.snap.txt +++ b/packages/rspack-test-tools/tests/hookCases/compilation#chunkHash/update-hash/hooks.snap.txt @@ -4,7 +4,7 @@ ```javascript Array [ - _Chunk { + Chunk { "auxiliaryFiles": Set {}, "chunkReason": undefined, "contentHash": Object {}, diff --git a/packages/rspack-test-tools/tests/hookCases/compiler#assetEmitted/basic/hooks.snap.txt b/packages/rspack-test-tools/tests/hookCases/compiler#assetEmitted/basic/hooks.snap.txt index 8a6472fa834..a1cbe9d4a2b 100644 --- a/packages/rspack-test-tools/tests/hookCases/compiler#assetEmitted/basic/hooks.snap.txt +++ b/packages/rspack-test-tools/tests/hookCases/compiler#assetEmitted/basic/hooks.snap.txt @@ -6,7 +6,7 @@ Array [ "main.js", Object { - "compilation": "_Compilation(internal ignored)", + "compilation": "Compilation(internal ignored)", "content": Object { "data": Array [ 40, diff --git a/packages/rspack-test-tools/tests/hookCases/javascriptModulesPlugin#chunkHash/update-hash/hooks.snap.txt b/packages/rspack-test-tools/tests/hookCases/javascriptModulesPlugin#chunkHash/update-hash/hooks.snap.txt index 93bb5f1ad44..203e4ebbda4 100644 --- a/packages/rspack-test-tools/tests/hookCases/javascriptModulesPlugin#chunkHash/update-hash/hooks.snap.txt +++ b/packages/rspack-test-tools/tests/hookCases/javascriptModulesPlugin#chunkHash/update-hash/hooks.snap.txt @@ -4,7 +4,7 @@ ```javascript Array [ - _Chunk { + Chunk { "auxiliaryFiles": Set {}, "chunkReason": undefined, "contentHash": Object {}, @@ -65595,7 +65595,7 @@ undefined ```javascript Array [ - _Chunk { + Chunk { "auxiliaryFiles": Set {}, "chunkReason": undefined, "contentHash": Object {}, diff --git a/packages/rspack-test-tools/tests/hotCases/css/recovery/__snapshots__/web/2.snap.txt b/packages/rspack-test-tools/tests/hotCases/css/recovery/__snapshots__/web/2.snap.txt index 441e4d510c9..2f7959f7473 100644 --- a/packages/rspack-test-tools/tests/hotCases/css/recovery/__snapshots__/web/2.snap.txt +++ b/packages/rspack-test-tools/tests/hotCases/css/recovery/__snapshots__/web/2.snap.txt @@ -6,7 +6,7 @@ ## Asset Files - Bundle: bundle.js - Manifest: main.LAST_HASH.hot-update.json, size: 28 -- Update: main.hot-update.js, size: 6905 +- Update: main.hot-update.js, size: 8241 ## Manifest @@ -27,235 +27,216 @@ - ./index.css #### Changed Runtime Modules +- webpack/runtime/define_property_getters - webpack/runtime/get_full_hash +- webpack/runtime/has_own_property +- webpack/runtime/make_namespace_object #### Changed Content ```js "use strict"; self["webpackHotUpdate"]('main', { -"../../../../../rspack/dist/cssExtractHmr.js": (function (module) { +"../../../../../rspack/dist/cssExtractHmr.js": (function (__unused_webpack_module, exports) { -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/runtime/cssExtractHmr.ts -var cssExtractHmr_exports = {}; -__export(cssExtractHmr_exports, { - cssReload: () => cssReload, - normalizeUrl: () => normalizeUrl +// The require scope +var __nested_webpack_require_39_58__ = {}; +/************************************************************************/ // webpack/runtime/define_property_getters +(()=>{ + __nested_webpack_require_39_58__.d = function(exports1, definition) { + for(var key in definition)if (__nested_webpack_require_39_58__.o(definition, key) && !__nested_webpack_require_39_58__.o(exports1, key)) Object.defineProperty(exports1, key, { + enumerable: true, + get: definition[key] + }); + }; +})(); +// webpack/runtime/has_own_property +(()=>{ + __nested_webpack_require_39_58__.o = function(obj, prop) { + return Object.prototype.hasOwnProperty.call(obj, prop); + }; +})(); +// webpack/runtime/make_namespace_object +(()=>{ + // define __esModule on exports + __nested_webpack_require_39_58__.r = function(exports1) { + if ('undefined' != typeof Symbol && Symbol.toStringTag) Object.defineProperty(exports1, Symbol.toStringTag, { + value: 'Module' + }); + Object.defineProperty(exports1, '__esModule', { + value: true + }); + }; +})(); +/************************************************************************/ var __nested_webpack_exports__ = {}; +__nested_webpack_require_39_58__.r(__nested_webpack_exports__); +__nested_webpack_require_39_58__.d(__nested_webpack_exports__, { + cssReload: function() { + return cssReload; + }, + normalizeUrl: function() { + return normalizeUrl; + } }); -module.exports = __toCommonJS(cssExtractHmr_exports); function normalizeUrl(url) { - const urlString = url.trim(); - if (/^data:/i.test(urlString)) { - return urlString; - } - const protocol = urlString.indexOf("//") !== -1 ? `${urlString.split("//")[0]}//` : ""; - const components = urlString.replace(new RegExp(protocol, "i"), "").split("/"); - const host = components[0].toLowerCase().replace(/\.$/, ""); - components[0] = ""; - const path = components.reduce((accumulator, item) => { - switch (item) { - case "..": - accumulator.pop(); - break; - case ".": - break; - default: - accumulator.push(item); - } - return accumulator; - }, []).join("/"); - return protocol + host + path; + const urlString = url.trim(); + if (/^data:/i.test(urlString)) return urlString; + const protocol = -1 !== urlString.indexOf("//") ? `${urlString.split("//")[0]}//` : ""; + const components = urlString.replace(new RegExp(protocol, "i"), "").split("/"); + const host = components[0].toLowerCase().replace(/\.$/, ""); + components[0] = ""; + const path = components.reduce((accumulator, item)=>{ + switch(item){ + case "..": + accumulator.pop(); + break; + case ".": + break; + default: + accumulator.push(item); + } + return accumulator; + }, []).join("/"); + return protocol + host + path; } -var srcByModuleId = /* @__PURE__ */ Object.create(null); -var noDocument = typeof document === "undefined"; -var { forEach } = Array.prototype; +const srcByModuleId = Object.create(null); +const noDocument = "undefined" == typeof document; +const { forEach } = Array.prototype; function debounce(fn, time) { - let timeout = 0; - return function(...args) { - const self = this; - const functionCall = function functionCall2() { - return fn.apply(self, args); + let timeout = 0; + return function() { + for(var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++)args[_key] = arguments[_key]; + const self = this; + const functionCall = function() { + return fn.apply(self, args); + }; + clearTimeout(timeout); + timeout = setTimeout(functionCall, time); }; - clearTimeout(timeout); - timeout = setTimeout(functionCall, time); - }; -} -function noop() { } +function noop() {} function getCurrentScriptUrl(moduleId) { - let src = srcByModuleId[moduleId]; - if (!src) { - if (document.currentScript) { - ({ src } = document.currentScript); - } else { - const scripts = document.getElementsByTagName("script"); - const lastScriptTag = scripts[scripts.length - 1]; - if (lastScriptTag) { - ({ src } = lastScriptTag); - } - } - srcByModuleId[moduleId] = src; - } - return (fileMap) => { + let src = srcByModuleId[moduleId]; if (!src) { - return null; - } - const splitResult = src.match(/([^\\/]+)\.js$/); - const filename = splitResult && splitResult[1]; - if (!filename || !fileMap) { - return [src.replace(".js", ".css")]; + if (document.currentScript) ({ src } = document.currentScript); + else { + const scripts = document.getElementsByTagName("script"); + const lastScriptTag = scripts[scripts.length - 1]; + if (lastScriptTag) ({ src } = lastScriptTag); + } + srcByModuleId[moduleId] = src; } - return fileMap.split(",").map((mapRule) => { - const reg = new RegExp(`${filename}\\.js$`, "g"); - return normalizeUrl( - src.replace(reg, `${mapRule.replace(/{fileName}/g, filename)}.css`) - ); - }); - }; + return (fileMap)=>{ + if (!src) return null; + const splitResult = src.match(/([^\\/]+)\.js$/); + // biome-ignore lint/complexity/useOptionalChain: not use optionalChain to support legacy browser + const filename = splitResult && splitResult[1]; + if (!filename || !fileMap) return [ + src.replace(".js", ".css") + ]; + return fileMap.split(",").map((mapRule)=>{ + const reg = new RegExp(`${filename}\\.js$`, "g"); + return normalizeUrl(src.replace(reg, `${mapRule.replace(/{fileName}/g, filename)}.css`)); + }); + }; } function updateCss(el, url) { - let normalizedUrl; - if (!url) { - if (!el.href) { - return; - } - normalizedUrl = el.href.split("?")[0]; - } else { - normalizedUrl = url; - } - if (!isUrlRequest(normalizedUrl)) { - return; - } - if (el.isLoaded === false) { - return; - } - if (!normalizedUrl || !(normalizedUrl.indexOf(".css") > -1)) { - return; - } - el.visited = true; - const newEl = el.cloneNode(); - newEl.isLoaded = false; - newEl.addEventListener("load", () => { - if (newEl.isLoaded) { - return; - } - newEl.isLoaded = true; - if (el.parentNode) { - el.parentNode.removeChild(el); - } - }); - newEl.addEventListener("error", () => { - if (newEl.isLoaded) { - return; - } - newEl.isLoaded = true; - if (el.parentNode) { - el.parentNode.removeChild(el); + let normalizedUrl; + if (url) normalizedUrl = url; + else { + if (!el.href) return; + normalizedUrl = el.href.split("?")[0]; } - }); - newEl.href = `${normalizedUrl}?${Date.now()}`; - const parent = el.parentNode; - if (!parent) { + if (!isUrlRequest(normalizedUrl)) return; + if (false === el.isLoaded) // We seem to be about to replace a css link that hasn't loaded yet. + // We're probably changing the same file more than once. return; - } - if (el.nextSibling) { - parent.insertBefore(newEl, el.nextSibling); - } else { - parent.appendChild(newEl); - } + if (!normalizedUrl || !(normalizedUrl.indexOf(".css") > -1)) return; + el.visited = true; + const newEl = el.cloneNode(); + newEl.isLoaded = false; + newEl.addEventListener("load", ()=>{ + if (newEl.isLoaded) return; + newEl.isLoaded = true; + if (el.parentNode) el.parentNode.removeChild(el); + }); + newEl.addEventListener("error", ()=>{ + if (newEl.isLoaded) return; + newEl.isLoaded = true; + if (el.parentNode) el.parentNode.removeChild(el); + }); + newEl.href = `${normalizedUrl}?${Date.now()}`; + const parent = el.parentNode; + if (!parent) return; + if (el.nextSibling) parent.insertBefore(newEl, el.nextSibling); + else parent.appendChild(newEl); } function getReloadUrl(href, src) { - let ret = ""; - const normalizedHref = normalizeUrl(href); - src.some((url) => { - if (normalizedHref.indexOf(src) > -1) { - ret = url; - } - }); - return ret; + let ret = ""; + const normalizedHref = normalizeUrl(href); + src.some((url)=>{ + if (normalizedHref.indexOf(src) > -1) ret = url; + }); + return ret; } function reloadStyle(src) { - if (!src) { - return false; - } - const elements = document.querySelectorAll("link"); - let loaded = false; - forEach.call(elements, (el) => { - if (!el.href) { - return; - } - const url = getReloadUrl(el.href, src); - if (!isUrlRequest(url)) { - return; - } - if (el.visited === true) { - return; - } - if (url) { - updateCss(el, url); - loaded = true; - } - }); - return loaded; + if (!src) return false; + const elements = document.querySelectorAll("link"); + let loaded = false; + forEach.call(elements, (el)=>{ + if (!el.href) return; + const url = getReloadUrl(el.href, src); + if (!isUrlRequest(url)) return; + if (true === el.visited) return; + if (url) { + updateCss(el, url); + loaded = true; + } + }); + return loaded; } function reloadAll() { - const elements = document.querySelectorAll("link"); - forEach.call(elements, (el) => { - if (el.visited === true) { - return; - } - updateCss(el); - }); + const elements = document.querySelectorAll("link"); + forEach.call(elements, (el)=>{ + if (true === el.visited) return; + updateCss(el); + }); } function isUrlRequest(url) { - if (!/^[a-zA-Z][a-zA-Z\d+\-.]*:/.test(url)) { - return false; - } - return true; + // An URL is not an request if + // It is not http or https + if (!/^[a-zA-Z][a-zA-Z\d+\-.]*:/.test(url)) return false; + return true; } function cssReload(moduleId, options) { - if (noDocument) { - console.log("[HMR] No `window.document` found, CSS HMR disabled"); - return noop; - } - const getScriptSrc = getCurrentScriptUrl(moduleId); - function update() { - const src = getScriptSrc(options.filename); - const reloaded = reloadStyle(src); - if (options.locals) { - console.log("[HMR] Detected local CSS Modules. Reload all CSS"); - reloadAll(); - return; + if (noDocument) { + console.log("[HMR] No `window.document` found, CSS HMR disabled"); + return noop; } - if (reloaded) { - console.log("[HMR] CSS reload %s", src && src.join(" ")); - } else { - console.log("[HMR] Reload all CSS"); - reloadAll(); + const getScriptSrc = getCurrentScriptUrl(moduleId); + function update() { + const src = getScriptSrc(options.filename); + const reloaded = reloadStyle(src); + if (options.locals) { + console.log("[HMR] Detected local CSS Modules. Reload all CSS"); + reloadAll(); + return; + } + if (reloaded) // biome-ignore lint/complexity/useOptionalChain: not use optionalChain to support legacy browser + console.log("[HMR] CSS reload %s", src && src.join(" ")); + else { + console.log("[HMR] Reload all CSS"); + reloadAll(); + } } - } - return debounce(update, 50); + return debounce(update, 50); } -// Annotate the CommonJS export names for ESM import in node: -0 && 0; +var __webpack_export_target__ = exports; +for(var i in __nested_webpack_exports__)__webpack_export_target__[i] = __nested_webpack_exports__[i]; +if (__nested_webpack_exports__.__esModule) Object.defineProperty(__webpack_export_target__, '__esModule', { + value: true +}); +0 && 0; }), "./index.css": (function (module, __webpack_exports__, __webpack_require__) { diff --git a/packages/rspack/package.json b/packages/rspack/package.json index e91c41c1980..9ca1ffb98cb 100644 --- a/packages/rspack/package.json +++ b/packages/rspack/package.json @@ -21,8 +21,9 @@ "./module": "./module.d.ts" }, "scripts": { - "build": "tsc -b ./tsconfig.build.json && tsc-alias -p tsconfig.build.json && tsup && npm run prepare-container-runtime", - "build:force": "tsc -b ./tsconfig.build.json --force && tsc-alias -p tsconfig.build.json && tsup && npm run prepare-container-runtime", + "build": "tsc -b ./tsconfig.build.json && tsc-alias -p tsconfig.build.json && rslib build && npm run prepare-container-runtime", + "build:tsup": "tsc -b ./tsconfig.build.json --force && tsc-alias -p tsconfig.build.json && tsup && npm run prepare-container-runtime", + "build:force": "tsc -b ./tsconfig.build.json --force && tsc-alias -p tsconfig.build.json && rslib build && npm run prepare-container-runtime", "dev": "pnpm run --stream /^dev:.*/", "dev:types": "tsc -w", "dev:js": "tsup --watch", @@ -51,6 +52,7 @@ "devDependencies": { "@swc/core": "1.10.1", "@swc/types": "0.1.17", + "@rslib/core": "0.1.4", "@types/graceful-fs": "4.1.9", "@types/watchpack": "^2.4.0", "@types/webpack-sources": "3.2.3", diff --git a/packages/rspack/rslib.config.ts b/packages/rspack/rslib.config.ts new file mode 100644 index 00000000000..ae6b72428e5 --- /dev/null +++ b/packages/rspack/rslib.config.ts @@ -0,0 +1,155 @@ +import { type LibConfig, defineConfig } from "@rslib/core"; +import prebundleConfig from "./prebundle.config.mjs"; + +const externalFunction = ({ request }: { request?: string }, callback) => { + const { dependencies } = prebundleConfig; + + for (const item of dependencies) { + const depName = typeof item === "string" ? item : item.name; + if (new RegExp(`^${depName}$`).test(request!)) { + return callback(null, `../compiled/${depName}/index.js`); + } + } + + if (/..\/package\.json/.test(request!)) { + return callback(null, "../package.json"); + } + + return callback(); +}; + +const commonLibConfig: LibConfig = { + dts: false, + format: "cjs", + syntax: ["node 16"], + source: { + define: { + __webpack_require__: "__webpack_require__" + } + }, + output: { + cleanDistPath: false, + // distPath: { + // root: "./dist-rslib" + // }, + externals: [externalFunction] + } +}; + +export default defineConfig({ + lib: [ + { + ...commonLibConfig, + source: { + entry: { + index: "./src/index.ts" + } + }, + output: { + ...commonLibConfig.output, + externals: [externalFunction, "./moduleFederationDefaultRuntime.js"] + }, + footer: { + js: ` + module.exports = rspack; + 0 && (module.exports = { + BannerPlugin, + Compilation, + Compiler, + ContextReplacementPlugin, + CopyRspackPlugin, + CssExtractRspackPlugin, + DefinePlugin, + DllPlugin, + DllReferencePlugin, + DynamicEntryPlugin, + EntryOptionPlugin, + EntryPlugin, + EnvironmentPlugin, + EvalDevToolModulePlugin, + EvalSourceMapDevToolPlugin, + ExternalsPlugin, + HotModuleReplacementPlugin, + HtmlRspackPlugin, + IgnorePlugin, + LightningCssMinimizerRspackPlugin, + LoaderOptionsPlugin, + LoaderTargetPlugin, + ModuleFilenameHelpers, + MultiCompiler, + MultiStats, + NoEmitOnErrorsPlugin, + NormalModule, + NormalModuleReplacementPlugin, + ProgressPlugin, + ProvidePlugin, + RspackOptionsApply, + RuntimeGlobals, + RuntimeModule, + SourceMapDevToolPlugin, + Stats, + SwcJsMinimizerRspackPlugin, + Template, + ValidationError, + WebpackError, + WebpackOptionsApply, + config, + container, + electron, + experiments, + javascript, + library, + node, + optimize, + rspack, + rspackVersion, + sharing, + sources, + util, + version, + wasm, + web, + webworker +}); +` + } + }, + { + ...commonLibConfig, + source: { + entry: { + cssExtractLoader: "./src/builtin-plugin/css-extract/loader.ts" + } + }, + footer: { + js: `0 && (module.exports = { + ABSOLUTE_PUBLIC_PATH, + AUTO_PUBLIC_PATH, + BASE_URI, + MODULE_TYPE, + SINGLE_DOT_PATH_SEGMENT, + hotLoader, + pitch +});` + } + }, + { + ...commonLibConfig, + syntax: "es2015", + source: { + entry: { + cssExtractHmr: "./src/runtime/cssExtractHmr.ts" + } + }, + footer: { + js: `0 && (module.exports = { + cssReload, + normalizeUrl +});` + } + } + ], + output: { + target: "node" + } +}); diff --git a/packages/rspack/src/Compiler.ts b/packages/rspack/src/Compiler.ts index f3f60dc8f6a..e2451ad4b02 100644 --- a/packages/rspack/src/Compiler.ts +++ b/packages/rspack/src/Compiler.ts @@ -1095,7 +1095,8 @@ class Compiler { codeGenerationResult: new CodeGenerationResult(result), moduleObject }, - { __webpack_require__ } + // What, transform bug? + { __webpack_require__: __webpack_require__ } ), "Compilation.hooks.executeModule" ); diff --git a/packages/rspack/src/index.ts b/packages/rspack/src/index.ts index 824b8161892..5adbf0541d0 100644 --- a/packages/rspack/src/index.ts +++ b/packages/rspack/src/index.ts @@ -11,4 +11,4 @@ const rspack: Rspack = fn; export * from "./exports"; export default rspack; export { rspack }; -module.exports = rspack; +// module.exports = rspack; diff --git a/packages/rspack/tsup.config.ts b/packages/rspack/tsup.config.ts index d9cdefc0c19..bcebba91dcb 100644 --- a/packages/rspack/tsup.config.ts +++ b/packages/rspack/tsup.config.ts @@ -24,7 +24,8 @@ const aliasPlugin = { const commonConfig: Options = { format: ["cjs"], target: "node16", - esbuildPlugins: [aliasPlugin] + esbuildPlugins: [aliasPlugin], + outDir: "./dist-modern" }; export default defineConfig([ diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 59b6311979a..09945a53fff 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -144,8 +144,8 @@ importers: version: 1.0.6 devDependencies: '@rslib/core': - specifier: 0.0.15 - version: 0.0.15(@microsoft/api-extractor@7.47.11(@types/node@20.12.7))(typescript@5.6.3) + specifier: 0.1.4 + version: 0.1.4(@microsoft/api-extractor@7.47.11(@types/node@20.12.7))(typescript@5.6.3) typescript: specifier: ^5.6.3 version: 5.6.3 @@ -310,6 +310,9 @@ importers: specifier: ^1.0.30001616 version: 1.0.30001676 devDependencies: + '@rslib/core': + specifier: 0.1.4 + version: 0.1.4(@microsoft/api-extractor@7.47.11(@types/node@20.12.7))(typescript@5.6.3) '@swc/core': specifier: 1.10.1 version: 1.10.1(@swc/helpers@0.5.13) @@ -399,8 +402,8 @@ importers: version: 17.6.2 devDependencies: '@rslib/core': - specifier: 0.0.15 - version: 0.0.15(@microsoft/api-extractor@7.47.11(@types/node@20.12.7))(typescript@5.6.3) + specifier: 0.1.4 + version: 0.1.4(@microsoft/api-extractor@7.47.11(@types/node@20.12.7))(typescript@5.6.3) '@rspack/core': specifier: workspace:* version: link:../rspack @@ -2841,11 +2844,6 @@ packages: cpu: [x64] os: [win32] - '@rsbuild/core@1.0.19': - resolution: {integrity: sha512-63DAPvYfRBoUrb51BUPb4Xoqx48MHQ0yLcmnCiqZGpMeKYtTWzD+lyx5va4cr9qvdnIFTAX2BMuYC/j5iSrtTA==} - engines: {node: '>=16.7.0'} - hasBin: true - '@rsbuild/core@1.1.10': resolution: {integrity: sha512-G0aVnoMSIZ4PNcW07tKtsOSoID9M03EAnCThRmUWMj1RXDqhbGje6AFBwGun9uz63bdxYEbEp9C8wH7dGi8aYQ==} engines: {node: '>=16.7.0'} @@ -2866,8 +2864,8 @@ packages: peerDependencies: '@rsbuild/core': 1.x - '@rslib/core@0.0.15': - resolution: {integrity: sha512-E44MHKIsEHB62CLH5UuhnUXlpdwW5aDYvEAvezJPhjqViI5odL5itTzAiKtVdHzBS4K3UZoP+o+pZRJ9vID0rQ==} + '@rslib/core@0.1.4': + resolution: {integrity: sha512-JyjSDxLTQmYg7UCASPOdjIY8VzNLsV2XR/liwdVf81nhendm2BuGB30wn76WEK0wxTkBZ1mPufwRCal0NMsjZw==} engines: {node: '>=16.0.0'} hasBin: true peerDependencies: @@ -2879,111 +2877,54 @@ packages: typescript: optional: true - '@rspack/binding-darwin-arm64@1.0.14': - resolution: {integrity: sha512-dHvlF6T6ctThGDIdvkSdacroA1xlCxfteuppBj8BX/UxzLPr4xsaEtNilfJmFfd2/J02UQyTQauN/9EBuA+YkA==} - cpu: [arm64] - os: [darwin] - '@rspack/binding-darwin-arm64@1.1.6': resolution: {integrity: sha512-x9dxm2yyiMuL1FBwvWNNMs2/mEUJmRoSRgYb8pblR7HDaTRORrjBFCqhaYlGyAqtQaeUy7o2VAQlE0BavIiFYA==} cpu: [arm64] os: [darwin] - '@rspack/binding-darwin-x64@1.0.14': - resolution: {integrity: sha512-q4Da1Bn/4xTLhhnOkT+fjP2STsSCfp4z03/J/h8tCVG/UYz56Ud3q1UEOK33c5Fxw1C4GlhEh5yYOlSAdxFQLQ==} - cpu: [x64] - os: [darwin] - '@rspack/binding-darwin-x64@1.1.6': resolution: {integrity: sha512-o0seilveftGiDjy3VPxug20HmAgYyQbNEuagR3i93/t/PT/eWXHnik+C1jjwqcivZL1Zllqvy4tbZw393aROEQ==} cpu: [x64] os: [darwin] - '@rspack/binding-linux-arm64-gnu@1.0.14': - resolution: {integrity: sha512-JogYtL3VQS9wJ3p3FNhDqinm7avrMsdwz4erP7YCjD7idob93GYAE7dPrHUzSNVnCBYXRaHJYZHDQs7lKVcYZw==} - cpu: [arm64] - os: [linux] - '@rspack/binding-linux-arm64-gnu@1.1.6': resolution: {integrity: sha512-4atnoknJx/c3KaQElsMIxHMpPf2jcRRdWsH/SdqJIRSrkWWakMK9Yv4TFwH680I4HDTMf1XLboMVScHzW8e+Mg==} cpu: [arm64] os: [linux] - '@rspack/binding-linux-arm64-musl@1.0.14': - resolution: {integrity: sha512-qgybhxI/nnoa8CUz7zKTC0Oh37NZt9uRxsSV7+ZYrfxqbrVCoNVuutPpY724uUHy1M6W34kVEm1uT1N4Ka5cZg==} - cpu: [arm64] - os: [linux] - '@rspack/binding-linux-arm64-musl@1.1.6': resolution: {integrity: sha512-7QMtwUtgFpt3/Y3/X18fSyN+kk4H8ZnZ8tDzQskVWc/j2AQYShZq56XQYqrhClzwujcCVAHauIQ2eiuJ2ASGag==} cpu: [arm64] os: [linux] - '@rspack/binding-linux-x64-gnu@1.0.14': - resolution: {integrity: sha512-5vzaDRw3/sGKo3ax/1cU3/cxqNjajwlt2LU288vXNe1/n8oe/pcDfYcTugpOe/A1DqzadanudJszLpFcKsaFtQ==} - cpu: [x64] - os: [linux] - '@rspack/binding-linux-x64-gnu@1.1.6': resolution: {integrity: sha512-MTjDEfPn4TwHoqs5d5Fck06kmXiTHZctGIcRVfrpg0RK0r1NLEHN+oosavRZ9c9H70f34+NmcHk+/qvV4c8lWg==} cpu: [x64] os: [linux] - '@rspack/binding-linux-x64-musl@1.0.14': - resolution: {integrity: sha512-4U6QD9xVS1eGme52DuJr6Fg/KdcUfJ+iKwH49Up460dZ/fLvGylnVGA+V0mzPlKi8gfy7NwFuYXZdu3Pwi1YYg==} - cpu: [x64] - os: [linux] - '@rspack/binding-linux-x64-musl@1.1.6': resolution: {integrity: sha512-LqDw7PTVr/4ZuGA0izgDQfamfr72USFHltR1Qhy2YVC3JmDmhG/pQi13LHcOLVaGH1xoeyCmEPNJpVizzDxSjg==} cpu: [x64] os: [linux] - '@rspack/binding-win32-arm64-msvc@1.0.14': - resolution: {integrity: sha512-SjeYw7qqRHYZ5RPClu+ffKZsShQdU3amA1OwC3M0AS6dbfEcji8482St3Y8Z+QSzYRapCEZij9LMM/9ypEhISg==} - cpu: [arm64] - os: [win32] - '@rspack/binding-win32-arm64-msvc@1.1.6': resolution: {integrity: sha512-RHApLM93YN0WdHpS35u2cm7VCqZ8Yg3CrNRL16VJtyT9e6MBqeScoe4XIgIWKPm7edFyedYAjLX0wQOApwfjkg==} cpu: [arm64] os: [win32] - '@rspack/binding-win32-ia32-msvc@1.0.14': - resolution: {integrity: sha512-m1gUiVyz3Z3VYIK/Ayo5CVHBjnEeRk9a+KIpKSsq1yhZItnMgjtr4bKabU9vjxalO4UoaSmVzODJI8lJBlnn5Q==} - cpu: [ia32] - os: [win32] - '@rspack/binding-win32-ia32-msvc@1.1.6': resolution: {integrity: sha512-Y6lx4q0eJawRfMPBo/AclTJAPTZ325DSPFBQJB3TnWh9Z2X7P7pQcYc8PHDmfDuYRIdg5WRsQRvVxihSvF7v8w==} cpu: [ia32] os: [win32] - '@rspack/binding-win32-x64-msvc@1.0.14': - resolution: {integrity: sha512-Gbeg+bayMF9VP9xmlxySL/TC2XrS6/LZM/pqcNOTLHx6LMG/VXCcmKB0rOZo8MzLXEt8D/lQmQ/B6g7pSaAw0g==} - cpu: [x64] - os: [win32] - '@rspack/binding-win32-x64-msvc@1.1.6': resolution: {integrity: sha512-UuCsfhC/yNuU7xLASOxNXcmsXi2ZvBX14GkxvcdChw6q7IIGNYUKXo1zgR8C1PE/6qDSxmLxbRMS+71d0H3HQg==} cpu: [x64] os: [win32] - '@rspack/binding@1.0.14': - resolution: {integrity: sha512-0wWqFvr9hkF4LgNPgWfkTU0hhkZAMvOytoCs2p+wDX1Up1E/SgJ1U1JAsCxsl1XtUKm7mRvdWHzJmHbza3y89Q==} - '@rspack/binding@1.1.6': resolution: {integrity: sha512-vfeBEgGOYVwqj5cQjGyvdfrr/BEihAHlyIsobL98FZjTF0uig+bj2yJUH5Ib5F0BpIUKVG3Pw0IjlUBqcVpZsQ==} - '@rspack/core@1.0.14': - resolution: {integrity: sha512-xHl23lxJZNjItGc5YuE9alz3yjb56y7EgJmAcBMPHMqgjtUt8rBu4xd/cSUjbr9/lLF9N4hdyoJiPJOFs9LEjw==} - engines: {node: '>=16.0.0'} - peerDependencies: - '@swc/helpers': '>=0.5.1' - peerDependenciesMeta: - '@swc/helpers': - optional: true - '@rspack/core@1.1.6': resolution: {integrity: sha512-q0VLphOF5VW2FEG7Vbdq3Ke4I74FbELE/8xmKghSalFtULLZ44SoSz8lyotfMim9GXIRFhDokAaH8WICmPxG+g==} engines: {node: '>=16.0.0'} @@ -6719,6 +6660,9 @@ packages: magic-string@0.30.12: resolution: {integrity: sha512-Ea8I3sQMVXr8JhN4z+H/d8zwo+tYDgHE9+5G4Wnrwhs0gaK9fXTKx0Tw5Xwsd/bCPTTZNRAdpyzvoeORe9LYpw==} + magic-string@0.30.17: + resolution: {integrity: sha512-sNPKHvyjVf7gyjwS4xGTaW/mCnF8wnjtifKBEhxfZ7E/S8tQ0rssrwGNn6q8JH/ohItJfSQp9mBtQYuTlH5QnA==} + make-dir@2.1.0: resolution: {integrity: sha512-LS9X+dc8KLxXCb8dni79fLIIUA5VyZoyjSMCwTluaXA0o27cCK0bhXkpgw+sTXVpPy/lSO57ilRixqk0vDmtRA==} engines: {node: '>=6'} @@ -8325,8 +8269,8 @@ packages: rrweb-cssom@0.7.1: resolution: {integrity: sha512-TrEMa7JGdVm0UThDJSx7ddw5nVm3UJS9o9CCIZ72B1vSyEZoziDqBYP3XIoi/12lKrJR8rE3jeFHMok2F/Mnsg==} - rsbuild-plugin-dts@0.0.15: - resolution: {integrity: sha512-KtM3BpyT7eXyLwVWHIRR4mGDUOoG3D/X4etRfZU6Wt+Qpd3ptwMHkcy2srY9MLQj2/cE7sOEPLuhDi3VQLtorw==} + rsbuild-plugin-dts@0.1.4: + resolution: {integrity: sha512-jqhkHGeswhH1Jfc/5zDX01UhrCwImquVjuZZXnAa34Cx0SEB+938WBIpAkyx3UEq7QLQDSII2z3pZ9cD/bpCTg==} engines: {node: '>=16.0.0'} peerDependencies: '@microsoft/api-extractor': ^7 @@ -11839,15 +11783,6 @@ snapshots: '@rollup/rollup-win32-x64-msvc@4.24.0': optional: true - '@rsbuild/core@1.0.19': - dependencies: - '@rspack/core': 1.0.14(@swc/helpers@0.5.15) - '@rspack/lite-tapable': 1.0.1 - '@swc/helpers': 0.5.15 - core-js: 3.38.1 - optionalDependencies: - fsevents: 2.3.3 - '@rsbuild/core@1.1.10': dependencies: '@rspack/core': 1.1.6(@swc/helpers@0.5.15) @@ -11876,81 +11811,42 @@ snapshots: reduce-configs: 1.1.0 sass-embedded: 1.83.0 - '@rslib/core@0.0.15(@microsoft/api-extractor@7.47.11(@types/node@20.12.7))(typescript@5.6.3)': + '@rslib/core@0.1.4(@microsoft/api-extractor@7.47.11(@types/node@20.12.7))(typescript@5.6.3)': dependencies: - '@rsbuild/core': 1.0.19 - rsbuild-plugin-dts: 0.0.15(@microsoft/api-extractor@7.47.11(@types/node@20.12.7))(@rsbuild/core@1.0.19)(typescript@5.6.3) + '@rsbuild/core': 1.1.10 + rsbuild-plugin-dts: 0.1.4(@microsoft/api-extractor@7.47.11(@types/node@20.12.7))(@rsbuild/core@1.1.10)(typescript@5.6.3) tinyglobby: 0.2.10 optionalDependencies: '@microsoft/api-extractor': 7.47.11(@types/node@20.12.7) typescript: 5.6.3 - '@rspack/binding-darwin-arm64@1.0.14': - optional: true - '@rspack/binding-darwin-arm64@1.1.6': optional: true - '@rspack/binding-darwin-x64@1.0.14': - optional: true - '@rspack/binding-darwin-x64@1.1.6': optional: true - '@rspack/binding-linux-arm64-gnu@1.0.14': - optional: true - '@rspack/binding-linux-arm64-gnu@1.1.6': optional: true - '@rspack/binding-linux-arm64-musl@1.0.14': - optional: true - '@rspack/binding-linux-arm64-musl@1.1.6': optional: true - '@rspack/binding-linux-x64-gnu@1.0.14': - optional: true - '@rspack/binding-linux-x64-gnu@1.1.6': optional: true - '@rspack/binding-linux-x64-musl@1.0.14': - optional: true - '@rspack/binding-linux-x64-musl@1.1.6': optional: true - '@rspack/binding-win32-arm64-msvc@1.0.14': - optional: true - '@rspack/binding-win32-arm64-msvc@1.1.6': optional: true - '@rspack/binding-win32-ia32-msvc@1.0.14': - optional: true - '@rspack/binding-win32-ia32-msvc@1.1.6': optional: true - '@rspack/binding-win32-x64-msvc@1.0.14': - optional: true - '@rspack/binding-win32-x64-msvc@1.1.6': optional: true - '@rspack/binding@1.0.14': - optionalDependencies: - '@rspack/binding-darwin-arm64': 1.0.14 - '@rspack/binding-darwin-x64': 1.0.14 - '@rspack/binding-linux-arm64-gnu': 1.0.14 - '@rspack/binding-linux-arm64-musl': 1.0.14 - '@rspack/binding-linux-x64-gnu': 1.0.14 - '@rspack/binding-linux-x64-musl': 1.0.14 - '@rspack/binding-win32-arm64-msvc': 1.0.14 - '@rspack/binding-win32-ia32-msvc': 1.0.14 - '@rspack/binding-win32-x64-msvc': 1.0.14 - '@rspack/binding@1.1.6': optionalDependencies: '@rspack/binding-darwin-arm64': 1.1.6 @@ -11963,15 +11859,6 @@ snapshots: '@rspack/binding-win32-ia32-msvc': 1.1.6 '@rspack/binding-win32-x64-msvc': 1.1.6 - '@rspack/core@1.0.14(@swc/helpers@0.5.15)': - dependencies: - '@module-federation/runtime-tools': 0.5.1 - '@rspack/binding': 1.0.14 - '@rspack/lite-tapable': 1.0.1 - caniuse-lite: 1.0.30001676 - optionalDependencies: - '@swc/helpers': 0.5.15 - '@rspack/core@1.1.6(@swc/helpers@0.5.15)': dependencies: '@module-federation/runtime-tools': 0.5.1 @@ -16460,6 +16347,10 @@ snapshots: dependencies: '@jridgewell/sourcemap-codec': 1.5.0 + magic-string@0.30.17: + dependencies: + '@jridgewell/sourcemap-codec': 1.5.0 + make-dir@2.1.0: dependencies: pify: 4.0.1 @@ -18492,10 +18383,10 @@ snapshots: rrweb-cssom@0.7.1: {} - rsbuild-plugin-dts@0.0.15(@microsoft/api-extractor@7.47.11(@types/node@20.12.7))(@rsbuild/core@1.0.19)(typescript@5.6.3): + rsbuild-plugin-dts@0.1.4(@microsoft/api-extractor@7.47.11(@types/node@20.12.7))(@rsbuild/core@1.1.10)(typescript@5.6.3): dependencies: - '@rsbuild/core': 1.0.19 - magic-string: 0.30.12 + '@rsbuild/core': 1.1.10 + magic-string: 0.30.17 picocolors: 1.1.1 tinyglobby: 0.2.10 optionalDependencies: diff --git a/tests/plugin-test/css-extract/cases/hmr-locals/expected/main.js b/tests/plugin-test/css-extract/cases/hmr-locals/expected/main.js index 95953705e03..c6cef4b688d 100644 --- a/tests/plugin-test/css-extract/cases/hmr-locals/expected/main.js +++ b/tests/plugin-test/css-extract/cases/hmr-locals/expected/main.js @@ -1,229 +1,207 @@ (() => { // webpackBootstrap "use strict"; var __webpack_modules__ = ({ -"../../../../../packages/rspack/dist/cssExtractHmr.js": (function (module) { - -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/runtime/cssExtractHmr.ts -var cssExtractHmr_exports = {}; -__export(cssExtractHmr_exports, { - cssReload: () => cssReload, - normalizeUrl: () => normalizeUrl +"../../../../../packages/rspack/dist/cssExtractHmr.js": (function (__unused_webpack_module, exports) { + +// The require scope +var __nested_webpack_require_39_58__ = {}; +/************************************************************************/ // webpack/runtime/define_property_getters +(()=>{ + __nested_webpack_require_39_58__.d = function(exports1, definition) { + for(var key in definition)if (__nested_webpack_require_39_58__.o(definition, key) && !__nested_webpack_require_39_58__.o(exports1, key)) Object.defineProperty(exports1, key, { + enumerable: true, + get: definition[key] + }); + }; +})(); +// webpack/runtime/has_own_property +(()=>{ + __nested_webpack_require_39_58__.o = function(obj, prop) { + return Object.prototype.hasOwnProperty.call(obj, prop); + }; +})(); +// webpack/runtime/make_namespace_object +(()=>{ + // define __esModule on exports + __nested_webpack_require_39_58__.r = function(exports1) { + if ('undefined' != typeof Symbol && Symbol.toStringTag) Object.defineProperty(exports1, Symbol.toStringTag, { + value: 'Module' + }); + Object.defineProperty(exports1, '__esModule', { + value: true + }); + }; +})(); +/************************************************************************/ var __nested_webpack_exports__ = {}; +__nested_webpack_require_39_58__.r(__nested_webpack_exports__); +__nested_webpack_require_39_58__.d(__nested_webpack_exports__, { + cssReload: function() { + return cssReload; + }, + normalizeUrl: function() { + return normalizeUrl; + } }); -module.exports = __toCommonJS(cssExtractHmr_exports); function normalizeUrl(url) { - const urlString = url.trim(); - if (/^data:/i.test(urlString)) { - return urlString; - } - const protocol = urlString.indexOf("//") !== -1 ? `${urlString.split("//")[0]}//` : ""; - const components = urlString.replace(new RegExp(protocol, "i"), "").split("/"); - const host = components[0].toLowerCase().replace(/\.$/, ""); - components[0] = ""; - const path = components.reduce((accumulator, item) => { - switch (item) { - case "..": - accumulator.pop(); - break; - case ".": - break; - default: - accumulator.push(item); - } - return accumulator; - }, []).join("/"); - return protocol + host + path; + const urlString = url.trim(); + if (/^data:/i.test(urlString)) return urlString; + const protocol = -1 !== urlString.indexOf("//") ? `${urlString.split("//")[0]}//` : ""; + const components = urlString.replace(new RegExp(protocol, "i"), "").split("/"); + const host = components[0].toLowerCase().replace(/\.$/, ""); + components[0] = ""; + const path = components.reduce((accumulator, item)=>{ + switch(item){ + case "..": + accumulator.pop(); + break; + case ".": + break; + default: + accumulator.push(item); + } + return accumulator; + }, []).join("/"); + return protocol + host + path; } -var srcByModuleId = /* @__PURE__ */ Object.create(null); -var noDocument = typeof document === "undefined"; -var { forEach } = Array.prototype; +const srcByModuleId = Object.create(null); +const noDocument = "undefined" == typeof document; +const { forEach } = Array.prototype; function debounce(fn, time) { - let timeout = 0; - return function(...args) { - const self = this; - const functionCall = function functionCall2() { - return fn.apply(self, args); + let timeout = 0; + return function() { + for(var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++)args[_key] = arguments[_key]; + const self = this; + const functionCall = function() { + return fn.apply(self, args); + }; + clearTimeout(timeout); + timeout = setTimeout(functionCall, time); }; - clearTimeout(timeout); - timeout = setTimeout(functionCall, time); - }; -} -function noop() { } +function noop() {} function getCurrentScriptUrl(moduleId) { - let src = srcByModuleId[moduleId]; - if (!src) { - if (document.currentScript) { - ({ src } = document.currentScript); - } else { - const scripts = document.getElementsByTagName("script"); - const lastScriptTag = scripts[scripts.length - 1]; - if (lastScriptTag) { - ({ src } = lastScriptTag); - } - } - srcByModuleId[moduleId] = src; - } - return (fileMap) => { + let src = srcByModuleId[moduleId]; if (!src) { - return null; - } - const splitResult = src.match(/([^\\/]+)\.js$/); - const filename = splitResult && splitResult[1]; - if (!filename || !fileMap) { - return [src.replace(".js", ".css")]; + if (document.currentScript) ({ src } = document.currentScript); + else { + const scripts = document.getElementsByTagName("script"); + const lastScriptTag = scripts[scripts.length - 1]; + if (lastScriptTag) ({ src } = lastScriptTag); + } + srcByModuleId[moduleId] = src; } - return fileMap.split(",").map((mapRule) => { - const reg = new RegExp(`${filename}\\.js$`, "g"); - return normalizeUrl( - src.replace(reg, `${mapRule.replace(/{fileName}/g, filename)}.css`) - ); - }); - }; + return (fileMap)=>{ + if (!src) return null; + const splitResult = src.match(/([^\\/]+)\.js$/); + // biome-ignore lint/complexity/useOptionalChain: not use optionalChain to support legacy browser + const filename = splitResult && splitResult[1]; + if (!filename || !fileMap) return [ + src.replace(".js", ".css") + ]; + return fileMap.split(",").map((mapRule)=>{ + const reg = new RegExp(`${filename}\\.js$`, "g"); + return normalizeUrl(src.replace(reg, `${mapRule.replace(/{fileName}/g, filename)}.css`)); + }); + }; } function updateCss(el, url) { - let normalizedUrl; - if (!url) { - if (!el.href) { - return; + let normalizedUrl; + if (url) normalizedUrl = url; + else { + if (!el.href) return; + normalizedUrl = el.href.split("?")[0]; } - normalizedUrl = el.href.split("?")[0]; - } else { - normalizedUrl = url; - } - if (!isUrlRequest(normalizedUrl)) { - return; - } - if (el.isLoaded === false) { + if (!isUrlRequest(normalizedUrl)) return; + if (false === el.isLoaded) // We seem to be about to replace a css link that hasn't loaded yet. + // We're probably changing the same file more than once. return; - } - if (!normalizedUrl || !(normalizedUrl.indexOf(".css") > -1)) { - return; - } - el.visited = true; - const newEl = el.cloneNode(); - newEl.isLoaded = false; - newEl.addEventListener("load", () => { - if (newEl.isLoaded) { - return; - } - newEl.isLoaded = true; - if (el.parentNode) { - el.parentNode.removeChild(el); - } - }); - newEl.addEventListener("error", () => { - if (newEl.isLoaded) { - return; - } - newEl.isLoaded = true; - if (el.parentNode) { - el.parentNode.removeChild(el); - } - }); - newEl.href = `${normalizedUrl}?${Date.now()}`; - const parent = el.parentNode; - if (!parent) { - return; - } - if (el.nextSibling) { - parent.insertBefore(newEl, el.nextSibling); - } else { - parent.appendChild(newEl); - } + if (!normalizedUrl || !(normalizedUrl.indexOf(".css") > -1)) return; + el.visited = true; + const newEl = el.cloneNode(); + newEl.isLoaded = false; + newEl.addEventListener("load", ()=>{ + if (newEl.isLoaded) return; + newEl.isLoaded = true; + if (el.parentNode) el.parentNode.removeChild(el); + }); + newEl.addEventListener("error", ()=>{ + if (newEl.isLoaded) return; + newEl.isLoaded = true; + if (el.parentNode) el.parentNode.removeChild(el); + }); + newEl.href = `${normalizedUrl}?${Date.now()}`; + const parent = el.parentNode; + if (!parent) return; + if (el.nextSibling) parent.insertBefore(newEl, el.nextSibling); + else parent.appendChild(newEl); } function getReloadUrl(href, src) { - let ret = ""; - const normalizedHref = normalizeUrl(href); - src.some((url) => { - if (normalizedHref.indexOf(src) > -1) { - ret = url; - } - }); - return ret; + let ret = ""; + const normalizedHref = normalizeUrl(href); + src.some((url)=>{ + if (normalizedHref.indexOf(src) > -1) ret = url; + }); + return ret; } function reloadStyle(src) { - if (!src) { - return false; - } - const elements = document.querySelectorAll("link"); - let loaded = false; - forEach.call(elements, (el) => { - if (!el.href) { - return; - } - const url = getReloadUrl(el.href, src); - if (!isUrlRequest(url)) { - return; - } - if (el.visited === true) { - return; - } - if (url) { - updateCss(el, url); - loaded = true; - } - }); - return loaded; + if (!src) return false; + const elements = document.querySelectorAll("link"); + let loaded = false; + forEach.call(elements, (el)=>{ + if (!el.href) return; + const url = getReloadUrl(el.href, src); + if (!isUrlRequest(url)) return; + if (true === el.visited) return; + if (url) { + updateCss(el, url); + loaded = true; + } + }); + return loaded; } function reloadAll() { - const elements = document.querySelectorAll("link"); - forEach.call(elements, (el) => { - if (el.visited === true) { - return; - } - updateCss(el); - }); + const elements = document.querySelectorAll("link"); + forEach.call(elements, (el)=>{ + if (true === el.visited) return; + updateCss(el); + }); } function isUrlRequest(url) { - if (!/^[a-zA-Z][a-zA-Z\d+\-.]*:/.test(url)) { - return false; - } - return true; + // An URL is not an request if + // It is not http or https + if (!/^[a-zA-Z][a-zA-Z\d+\-.]*:/.test(url)) return false; + return true; } function cssReload(moduleId, options) { - if (noDocument) { - console.log("[HMR] No `window.document` found, CSS HMR disabled"); - return noop; - } - const getScriptSrc = getCurrentScriptUrl(moduleId); - function update() { - const src = getScriptSrc(options.filename); - const reloaded = reloadStyle(src); - if (options.locals) { - console.log("[HMR] Detected local CSS Modules. Reload all CSS"); - reloadAll(); - return; + if (noDocument) { + console.log("[HMR] No `window.document` found, CSS HMR disabled"); + return noop; } - if (reloaded) { - console.log("[HMR] CSS reload %s", src && src.join(" ")); - } else { - console.log("[HMR] Reload all CSS"); - reloadAll(); + const getScriptSrc = getCurrentScriptUrl(moduleId); + function update() { + const src = getScriptSrc(options.filename); + const reloaded = reloadStyle(src); + if (options.locals) { + console.log("[HMR] Detected local CSS Modules. Reload all CSS"); + reloadAll(); + return; + } + if (reloaded) // biome-ignore lint/complexity/useOptionalChain: not use optionalChain to support legacy browser + console.log("[HMR] CSS reload %s", src && src.join(" ")); + else { + console.log("[HMR] Reload all CSS"); + reloadAll(); + } } - } - return debounce(update, 50); + return debounce(update, 50); } -// Annotate the CommonJS export names for ESM import in node: -0 && 0; +var __webpack_export_target__ = exports; +for(var i in __nested_webpack_exports__)__webpack_export_target__[i] = __nested_webpack_exports__[i]; +if (__nested_webpack_exports__.__esModule) Object.defineProperty(__webpack_export_target__, '__esModule', { + value: true +}); +0 && 0; }), "./index.css": (function (module, __webpack_exports__, __webpack_require__) { diff --git a/tests/plugin-test/css-extract/cases/hmr/expected/main.js b/tests/plugin-test/css-extract/cases/hmr/expected/main.js index 8a924f282b0..1ad978a6438 100644 --- a/tests/plugin-test/css-extract/cases/hmr/expected/main.js +++ b/tests/plugin-test/css-extract/cases/hmr/expected/main.js @@ -1,229 +1,207 @@ (() => { // webpackBootstrap "use strict"; var __webpack_modules__ = ({ -"../../../../../packages/rspack/dist/cssExtractHmr.js": (function (module) { - -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/runtime/cssExtractHmr.ts -var cssExtractHmr_exports = {}; -__export(cssExtractHmr_exports, { - cssReload: () => cssReload, - normalizeUrl: () => normalizeUrl +"../../../../../packages/rspack/dist/cssExtractHmr.js": (function (__unused_webpack_module, exports) { + +// The require scope +var __nested_webpack_require_39_58__ = {}; +/************************************************************************/ // webpack/runtime/define_property_getters +(()=>{ + __nested_webpack_require_39_58__.d = function(exports1, definition) { + for(var key in definition)if (__nested_webpack_require_39_58__.o(definition, key) && !__nested_webpack_require_39_58__.o(exports1, key)) Object.defineProperty(exports1, key, { + enumerable: true, + get: definition[key] + }); + }; +})(); +// webpack/runtime/has_own_property +(()=>{ + __nested_webpack_require_39_58__.o = function(obj, prop) { + return Object.prototype.hasOwnProperty.call(obj, prop); + }; +})(); +// webpack/runtime/make_namespace_object +(()=>{ + // define __esModule on exports + __nested_webpack_require_39_58__.r = function(exports1) { + if ('undefined' != typeof Symbol && Symbol.toStringTag) Object.defineProperty(exports1, Symbol.toStringTag, { + value: 'Module' + }); + Object.defineProperty(exports1, '__esModule', { + value: true + }); + }; +})(); +/************************************************************************/ var __nested_webpack_exports__ = {}; +__nested_webpack_require_39_58__.r(__nested_webpack_exports__); +__nested_webpack_require_39_58__.d(__nested_webpack_exports__, { + cssReload: function() { + return cssReload; + }, + normalizeUrl: function() { + return normalizeUrl; + } }); -module.exports = __toCommonJS(cssExtractHmr_exports); function normalizeUrl(url) { - const urlString = url.trim(); - if (/^data:/i.test(urlString)) { - return urlString; - } - const protocol = urlString.indexOf("//") !== -1 ? `${urlString.split("//")[0]}//` : ""; - const components = urlString.replace(new RegExp(protocol, "i"), "").split("/"); - const host = components[0].toLowerCase().replace(/\.$/, ""); - components[0] = ""; - const path = components.reduce((accumulator, item) => { - switch (item) { - case "..": - accumulator.pop(); - break; - case ".": - break; - default: - accumulator.push(item); - } - return accumulator; - }, []).join("/"); - return protocol + host + path; + const urlString = url.trim(); + if (/^data:/i.test(urlString)) return urlString; + const protocol = -1 !== urlString.indexOf("//") ? `${urlString.split("//")[0]}//` : ""; + const components = urlString.replace(new RegExp(protocol, "i"), "").split("/"); + const host = components[0].toLowerCase().replace(/\.$/, ""); + components[0] = ""; + const path = components.reduce((accumulator, item)=>{ + switch(item){ + case "..": + accumulator.pop(); + break; + case ".": + break; + default: + accumulator.push(item); + } + return accumulator; + }, []).join("/"); + return protocol + host + path; } -var srcByModuleId = /* @__PURE__ */ Object.create(null); -var noDocument = typeof document === "undefined"; -var { forEach } = Array.prototype; +const srcByModuleId = Object.create(null); +const noDocument = "undefined" == typeof document; +const { forEach } = Array.prototype; function debounce(fn, time) { - let timeout = 0; - return function(...args) { - const self = this; - const functionCall = function functionCall2() { - return fn.apply(self, args); + let timeout = 0; + return function() { + for(var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++)args[_key] = arguments[_key]; + const self = this; + const functionCall = function() { + return fn.apply(self, args); + }; + clearTimeout(timeout); + timeout = setTimeout(functionCall, time); }; - clearTimeout(timeout); - timeout = setTimeout(functionCall, time); - }; -} -function noop() { } +function noop() {} function getCurrentScriptUrl(moduleId) { - let src = srcByModuleId[moduleId]; - if (!src) { - if (document.currentScript) { - ({ src } = document.currentScript); - } else { - const scripts = document.getElementsByTagName("script"); - const lastScriptTag = scripts[scripts.length - 1]; - if (lastScriptTag) { - ({ src } = lastScriptTag); - } - } - srcByModuleId[moduleId] = src; - } - return (fileMap) => { + let src = srcByModuleId[moduleId]; if (!src) { - return null; - } - const splitResult = src.match(/([^\\/]+)\.js$/); - const filename = splitResult && splitResult[1]; - if (!filename || !fileMap) { - return [src.replace(".js", ".css")]; + if (document.currentScript) ({ src } = document.currentScript); + else { + const scripts = document.getElementsByTagName("script"); + const lastScriptTag = scripts[scripts.length - 1]; + if (lastScriptTag) ({ src } = lastScriptTag); + } + srcByModuleId[moduleId] = src; } - return fileMap.split(",").map((mapRule) => { - const reg = new RegExp(`${filename}\\.js$`, "g"); - return normalizeUrl( - src.replace(reg, `${mapRule.replace(/{fileName}/g, filename)}.css`) - ); - }); - }; + return (fileMap)=>{ + if (!src) return null; + const splitResult = src.match(/([^\\/]+)\.js$/); + // biome-ignore lint/complexity/useOptionalChain: not use optionalChain to support legacy browser + const filename = splitResult && splitResult[1]; + if (!filename || !fileMap) return [ + src.replace(".js", ".css") + ]; + return fileMap.split(",").map((mapRule)=>{ + const reg = new RegExp(`${filename}\\.js$`, "g"); + return normalizeUrl(src.replace(reg, `${mapRule.replace(/{fileName}/g, filename)}.css`)); + }); + }; } function updateCss(el, url) { - let normalizedUrl; - if (!url) { - if (!el.href) { - return; + let normalizedUrl; + if (url) normalizedUrl = url; + else { + if (!el.href) return; + normalizedUrl = el.href.split("?")[0]; } - normalizedUrl = el.href.split("?")[0]; - } else { - normalizedUrl = url; - } - if (!isUrlRequest(normalizedUrl)) { - return; - } - if (el.isLoaded === false) { + if (!isUrlRequest(normalizedUrl)) return; + if (false === el.isLoaded) // We seem to be about to replace a css link that hasn't loaded yet. + // We're probably changing the same file more than once. return; - } - if (!normalizedUrl || !(normalizedUrl.indexOf(".css") > -1)) { - return; - } - el.visited = true; - const newEl = el.cloneNode(); - newEl.isLoaded = false; - newEl.addEventListener("load", () => { - if (newEl.isLoaded) { - return; - } - newEl.isLoaded = true; - if (el.parentNode) { - el.parentNode.removeChild(el); - } - }); - newEl.addEventListener("error", () => { - if (newEl.isLoaded) { - return; - } - newEl.isLoaded = true; - if (el.parentNode) { - el.parentNode.removeChild(el); - } - }); - newEl.href = `${normalizedUrl}?${Date.now()}`; - const parent = el.parentNode; - if (!parent) { - return; - } - if (el.nextSibling) { - parent.insertBefore(newEl, el.nextSibling); - } else { - parent.appendChild(newEl); - } + if (!normalizedUrl || !(normalizedUrl.indexOf(".css") > -1)) return; + el.visited = true; + const newEl = el.cloneNode(); + newEl.isLoaded = false; + newEl.addEventListener("load", ()=>{ + if (newEl.isLoaded) return; + newEl.isLoaded = true; + if (el.parentNode) el.parentNode.removeChild(el); + }); + newEl.addEventListener("error", ()=>{ + if (newEl.isLoaded) return; + newEl.isLoaded = true; + if (el.parentNode) el.parentNode.removeChild(el); + }); + newEl.href = `${normalizedUrl}?${Date.now()}`; + const parent = el.parentNode; + if (!parent) return; + if (el.nextSibling) parent.insertBefore(newEl, el.nextSibling); + else parent.appendChild(newEl); } function getReloadUrl(href, src) { - let ret = ""; - const normalizedHref = normalizeUrl(href); - src.some((url) => { - if (normalizedHref.indexOf(src) > -1) { - ret = url; - } - }); - return ret; + let ret = ""; + const normalizedHref = normalizeUrl(href); + src.some((url)=>{ + if (normalizedHref.indexOf(src) > -1) ret = url; + }); + return ret; } function reloadStyle(src) { - if (!src) { - return false; - } - const elements = document.querySelectorAll("link"); - let loaded = false; - forEach.call(elements, (el) => { - if (!el.href) { - return; - } - const url = getReloadUrl(el.href, src); - if (!isUrlRequest(url)) { - return; - } - if (el.visited === true) { - return; - } - if (url) { - updateCss(el, url); - loaded = true; - } - }); - return loaded; + if (!src) return false; + const elements = document.querySelectorAll("link"); + let loaded = false; + forEach.call(elements, (el)=>{ + if (!el.href) return; + const url = getReloadUrl(el.href, src); + if (!isUrlRequest(url)) return; + if (true === el.visited) return; + if (url) { + updateCss(el, url); + loaded = true; + } + }); + return loaded; } function reloadAll() { - const elements = document.querySelectorAll("link"); - forEach.call(elements, (el) => { - if (el.visited === true) { - return; - } - updateCss(el); - }); + const elements = document.querySelectorAll("link"); + forEach.call(elements, (el)=>{ + if (true === el.visited) return; + updateCss(el); + }); } function isUrlRequest(url) { - if (!/^[a-zA-Z][a-zA-Z\d+\-.]*:/.test(url)) { - return false; - } - return true; + // An URL is not an request if + // It is not http or https + if (!/^[a-zA-Z][a-zA-Z\d+\-.]*:/.test(url)) return false; + return true; } function cssReload(moduleId, options) { - if (noDocument) { - console.log("[HMR] No `window.document` found, CSS HMR disabled"); - return noop; - } - const getScriptSrc = getCurrentScriptUrl(moduleId); - function update() { - const src = getScriptSrc(options.filename); - const reloaded = reloadStyle(src); - if (options.locals) { - console.log("[HMR] Detected local CSS Modules. Reload all CSS"); - reloadAll(); - return; + if (noDocument) { + console.log("[HMR] No `window.document` found, CSS HMR disabled"); + return noop; } - if (reloaded) { - console.log("[HMR] CSS reload %s", src && src.join(" ")); - } else { - console.log("[HMR] Reload all CSS"); - reloadAll(); + const getScriptSrc = getCurrentScriptUrl(moduleId); + function update() { + const src = getScriptSrc(options.filename); + const reloaded = reloadStyle(src); + if (options.locals) { + console.log("[HMR] Detected local CSS Modules. Reload all CSS"); + reloadAll(); + return; + } + if (reloaded) // biome-ignore lint/complexity/useOptionalChain: not use optionalChain to support legacy browser + console.log("[HMR] CSS reload %s", src && src.join(" ")); + else { + console.log("[HMR] Reload all CSS"); + reloadAll(); + } } - } - return debounce(update, 50); + return debounce(update, 50); } -// Annotate the CommonJS export names for ESM import in node: -0 && 0; +var __webpack_export_target__ = exports; +for(var i in __nested_webpack_exports__)__webpack_export_target__[i] = __nested_webpack_exports__[i]; +if (__nested_webpack_exports__.__esModule) Object.defineProperty(__webpack_export_target__, '__esModule', { + value: true +}); +0 && 0; }), "./index.css": (function (module, __webpack_exports__, __webpack_require__) {