Skip to content

Commit 9b938ef

Browse files
committed
feat: hmr, compare old locals to invalidate if needed
1 parent d18cbfc commit 9b938ef

File tree

2 files changed

+61
-5
lines changed

2 files changed

+61
-5
lines changed

src/hmr/isEqualLocals.js

+33
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
function isEqualLocals(a, b, isNamedExport) {
2+
if ((!a && b) || (a && !b)) {
3+
return false;
4+
}
5+
6+
let p;
7+
8+
for (p in a) {
9+
if (isNamedExport && p === 'default') {
10+
// eslint-disable-next-line no-continue
11+
continue;
12+
}
13+
14+
if (a[p] !== b[p]) {
15+
return false;
16+
}
17+
}
18+
19+
for (p in b) {
20+
if (isNamedExport && p === 'default') {
21+
// eslint-disable-next-line no-continue
22+
continue;
23+
}
24+
25+
if (!a[p]) {
26+
return false;
27+
}
28+
}
29+
30+
return true;
31+
}
32+
33+
module.exports = isEqualLocals;

src/loader.js

+28-5
Original file line numberDiff line numberDiff line change
@@ -16,9 +16,19 @@ import schema from './loader-options.json';
1616
const pluginName = 'mini-css-extract-plugin';
1717

1818
function hotLoader(content, context) {
19-
const accept = context.locals
20-
? ''
21-
: 'module.hot.accept(undefined, cssReload);';
19+
const accept = `
20+
if (!_locals || module.hot.invalidate) {
21+
if (module.hot.invalidate &&
22+
module.hot.data &&
23+
module.hot.data.oldLocals &&
24+
!isEqualLocals(module.hot.data.oldLocals, _locals, ${JSON.stringify(
25+
context.namedExport
26+
)})) {
27+
module.hot.invalidate();
28+
} else {
29+
module.hot.accept();
30+
}
31+
}`;
2232

2333
return `${content}
2434
if(module.hot) {
@@ -30,7 +40,15 @@ function hotLoader(content, context) {
3040
...context.options,
3141
locals: !!context.locals,
3242
})});
33-
module.hot.dispose(cssReload);
43+
var _locals = ${JSON.stringify(context.locals)};
44+
var isEqualLocals = require(${loaderUtils.stringifyRequest(
45+
context.context,
46+
path.join(__dirname, 'hmr/isEqualLocals.js')
47+
)});
48+
module.hot.dispose(function(data) {
49+
cssReload();
50+
data.oldLocals = _locals;
51+
});
3452
${accept}
3553
}
3654
`;
@@ -269,7 +287,12 @@ export function pitch(request) {
269287
let resultSource = `// extracted by ${pluginName}`;
270288

271289
resultSource += this.hot
272-
? hotLoader(result, { context: this.context, options, locals })
290+
? hotLoader(result, {
291+
context: this.context,
292+
options,
293+
locals,
294+
namedExport,
295+
})
273296
: result;
274297

275298
return callback(null, resultSource);

0 commit comments

Comments
 (0)