Skip to content

Commit

Permalink
fix: avoid reload all css when hot load
Browse files Browse the repository at this point in the history
  • Loading branch information
yiminghe committed Mar 28, 2024
1 parent 8bf0ad6 commit e9bf629
Show file tree
Hide file tree
Showing 6 changed files with 1,672 additions and 18 deletions.
37 changes: 23 additions & 14 deletions src/loader.js
Original file line number Diff line number Diff line change
Expand Up @@ -44,22 +44,31 @@ const MiniCssExtractPlugin = require("./index");
* @returns {string}
*/
function hotLoader(content, context) {
const accept = context.locals
? ""
: "module.hot.accept(undefined, cssReload);";

const localsJsonString = JSON.stringify(JSON.stringify(context.locals));
return `${content}
if(module.hot) {
// ${Date.now()}
var cssReload = require(${stringifyRequest(
context.loaderContext,
path.join(__dirname, "hmr/hotModuleReplacement.js")
)})(module.id, ${JSON.stringify({
...context.options,
locals: !!context.locals,
})});
module.hot.dispose(cssReload);
${accept}
(function() {
var localsJsonString = ${localsJsonString};
// ${Date.now()}
var cssReload = require(${stringifyRequest(
context.loaderContext,
path.join(__dirname, "hmr/hotModuleReplacement.js")
)})(module.id, ${JSON.stringify(context.options)});
// only invalidate when locals change
if (
module.hot.data &&
module.hot.data.value &&
module.hot.data.value !== localsJsonString
) {
module.hot.invalidate();
} else {
module.hot.accept();
}
module.hot.dispose(function(data) {
data.value = localsJsonString;
cssReload();
});
})();
}
`;
}
Expand Down
7 changes: 7 additions & 0 deletions test/cases/hmr-locals/expected/main.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
/*!************************************************************************************************!*\
!*** css ../../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[0].use[1]!./index.css ***!
\************************************************************************************************/
.VoofDB21D_QzDbRdwMiY {
color: red;
}

Loading

0 comments on commit e9bf629

Please sign in to comment.