Skip to content

Commit 6727f11

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

File tree

2 files changed

+49
-5
lines changed

2 files changed

+49
-5
lines changed

src/hmr/isEqualLocals.js

+23
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
function isEqualLocals(a, b) {
2+
if ((!a && b) || (a && !b)) {
3+
return false;
4+
}
5+
6+
let p;
7+
8+
for (p in a) {
9+
if (a[p] !== b[p]) {
10+
return false;
11+
}
12+
}
13+
14+
for (p in b) {
15+
if (!a[p]) {
16+
return false;
17+
}
18+
}
19+
20+
return true;
21+
}
22+
23+
module.exports = isEqualLocals;

src/loader.js

+26-5
Original file line numberDiff line numberDiff line change
@@ -16,9 +16,17 @@ 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)) {
25+
module.hot.invalidate();
26+
} else {
27+
module.hot.accept();
28+
}
29+
}`;
2230

2331
return `${content}
2432
if(module.hot) {
@@ -30,7 +38,15 @@ function hotLoader(content, context) {
3038
...context.options,
3139
locals: !!context.locals,
3240
})});
33-
module.hot.dispose(cssReload);
41+
var _locals = ${JSON.stringify(context.locals)};
42+
var isEqualLocals = require(${loaderUtils.stringifyRequest(
43+
context.context,
44+
path.join(__dirname, 'hmr/isEqualLocals.js')
45+
)});
46+
module.hot.dispose(function(data) {
47+
cssReload();
48+
data.oldLocals = _locals;
49+
});
3450
${accept}
3551
}
3652
`;
@@ -269,7 +285,12 @@ export function pitch(request) {
269285
let resultSource = `// extracted by ${pluginName}`;
270286

271287
resultSource += this.hot
272-
? hotLoader(result, { context: this.context, options, locals })
288+
? hotLoader(result, {
289+
context: this.context,
290+
options,
291+
locals,
292+
namedExport,
293+
})
273294
: result;
274295

275296
return callback(null, resultSource);

0 commit comments

Comments
 (0)