Skip to content

Commit

Permalink
feat: hmr, compare old locals to invalidate if needed
Browse files Browse the repository at this point in the history
  • Loading branch information
goloveychuk committed Feb 2, 2021
1 parent d18cbfc commit 9b938ef
Show file tree
Hide file tree
Showing 2 changed files with 61 additions and 5 deletions.
33 changes: 33 additions & 0 deletions src/hmr/isEqualLocals.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
function isEqualLocals(a, b, isNamedExport) {
if ((!a && b) || (a && !b)) {
return false;
}

let p;

for (p in a) {
if (isNamedExport && p === 'default') {
// eslint-disable-next-line no-continue
continue;
}

if (a[p] !== b[p]) {
return false;
}
}

for (p in b) {
if (isNamedExport && p === 'default') {
// eslint-disable-next-line no-continue
continue;
}

if (!a[p]) {
return false;
}
}

return true;
}

module.exports = isEqualLocals;
33 changes: 28 additions & 5 deletions src/loader.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,19 @@ import schema from './loader-options.json';
const pluginName = 'mini-css-extract-plugin';

function hotLoader(content, context) {
const accept = context.locals
? ''
: 'module.hot.accept(undefined, cssReload);';
const accept = `
if (!_locals || module.hot.invalidate) {
if (module.hot.invalidate &&
module.hot.data &&
module.hot.data.oldLocals &&
!isEqualLocals(module.hot.data.oldLocals, _locals, ${JSON.stringify(
context.namedExport
)})) {
module.hot.invalidate();
} else {
module.hot.accept();
}
}`;

return `${content}
if(module.hot) {
Expand All @@ -30,7 +40,15 @@ function hotLoader(content, context) {
...context.options,
locals: !!context.locals,
})});
module.hot.dispose(cssReload);
var _locals = ${JSON.stringify(context.locals)};
var isEqualLocals = require(${loaderUtils.stringifyRequest(
context.context,
path.join(__dirname, 'hmr/isEqualLocals.js')
)});
module.hot.dispose(function(data) {
cssReload();
data.oldLocals = _locals;
});
${accept}
}
`;
Expand Down Expand Up @@ -269,7 +287,12 @@ export function pitch(request) {
let resultSource = `// extracted by ${pluginName}`;

resultSource += this.hot
? hotLoader(result, { context: this.context, options, locals })
? hotLoader(result, {
context: this.context,
options,
locals,
namedExport,
})
: result;

return callback(null, resultSource);
Expand Down

0 comments on commit 9b938ef

Please sign in to comment.