Skip to content

Commit e75dbde

Browse files
committed
refactor: use WeakMap
1 parent b111ffd commit e75dbde

File tree

1 file changed

+15
-11
lines changed

1 file changed

+15
-11
lines changed

src/utils.js

Lines changed: 15 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -651,7 +651,7 @@ function getWebpackImporter(loaderContext, implementation, includePaths) {
651651
}
652652

653653
let nodeSassJobQueue = null;
654-
const sassModernCompilers = {};
654+
const sassModernCompilers = new WeakMap();
655655

656656
/**
657657
* Verifies that the implementation and version of Sass is supported by this loader.
@@ -662,10 +662,11 @@ const sassModernCompilers = {};
662662
* @returns {Function}
663663
*/
664664
function getCompileFn(loaderContext, implementation, options) {
665-
const isDartSass = implementation.info.includes("dart-sass");
666-
const isSassEmbedded = implementation.info.includes("sass-embedded");
665+
const isNewSass =
666+
implementation.info.includes("dart-sass") ||
667+
implementation.info.includes("sass-embedded");
667668

668-
if (isDartSass || isSassEmbedded) {
669+
if (isNewSass) {
669670
if (options.api === "modern") {
670671
return (sassOptions) => {
671672
const { data, ...rest } = sassOptions;
@@ -683,17 +684,20 @@ function getCompileFn(loaderContext, implementation, options) {
683684
// Some people can run the loader in a multi-threading way;
684685
// there is no webpack compiler object in such case.
685686
if (webpackCompiler) {
686-
const key = isDartSass ? "dart-sass" : "sass-embedded";
687-
if (!sassModernCompilers[key]) {
687+
if (!sassModernCompilers.has(implementation)) {
688688
// Create a long-running compiler process that can be reused
689689
// for compiling individual files.
690690
const compiler = await implementation.initAsyncCompiler();
691-
webpackCompiler.hooks.shutdown.tap("sass-loader", () => {
692-
compiler.dispose();
693-
});
694-
sassModernCompilers[key] = compiler;
691+
// Check again because awaiting the initialization function
692+
// introduces a race condition.
693+
if (!sassModernCompilers.has(implementation)) {
694+
sassModernCompilers.set(implementation, compiler);
695+
webpackCompiler.hooks.shutdown.tap("sass-loader", () => {
696+
compiler.dispose();
697+
});
698+
}
695699
}
696-
return sassModernCompilers[key].compileStringAsync(data, rest);
700+
return sassModernCompilers.get(implementation).compileStringAsync(data, rest);
697701
}
698702

699703
return implementation.compileStringAsync(data, rest);

0 commit comments

Comments
 (0)