From db5d1befe075e05857f7fa32c2d118430f860c79 Mon Sep 17 00:00:00 2001 From: Vlad Ivanov Date: Mon, 24 Oct 2022 23:57:16 +0200 Subject: [PATCH] feat(loader): add functions support for locals --- src/loader.js | 15 +++++++++------ src/utils.js | 22 ++++++++++++++++++++++ 2 files changed, 31 insertions(+), 6 deletions(-) diff --git a/src/loader.js b/src/loader.js index 6de4e3d6..616b5abc 100644 --- a/src/loader.js +++ b/src/loader.js @@ -8,6 +8,8 @@ const { BASE_URI, SINGLE_DOT_PATH_SEGMENT, stringifyRequest, + stringifyLocals, + stringifyLocal, } = require("./utils"); const schema = require("./loader-options.json"); @@ -38,7 +40,7 @@ const MiniCssExtractPlugin = require("./index"); /** * @param {string} content - * @param {{ loaderContext: import("webpack").LoaderContext, options: LoaderOptions, locals: {[key: string]: string } | undefined }} context + * @param {{ loaderContext: import("webpack").LoaderContext, options: LoaderOptions, locals: { [key: string]: string | function } | undefined }} context * @returns {string} */ function hotLoader(content, context) { @@ -95,7 +97,7 @@ function pitch(request) { * @returns {void} */ const handleExports = (originalExports, compilation, assets, assetsInfo) => { - /** @type {{[key: string]: string } | undefined} */ + /** @type {{[key: string]: string | function } | undefined} */ let locals; let namedExport; @@ -228,15 +230,16 @@ function pitch(request) { ? Object.keys(locals) .map( (key) => - `\nexport var ${key} = ${JSON.stringify( - /** @type {{[key: string]: string }} */ - (locals)[key] + `\nexport var ${key} = ${stringifyLocal( + /** @type {{ [key: string]: string | function }} */ (locals)[ + key + ] )};` ) .join("") : `\n${ esModule ? "export default" : "module.exports =" - } ${JSON.stringify(locals)};` + } ${stringifyLocals(locals)};` : esModule ? `\nexport {};` : ""; diff --git a/src/utils.js b/src/utils.js index 416b38c1..998de604 100644 --- a/src/utils.js +++ b/src/utils.js @@ -205,6 +205,26 @@ function getUndoPath(filename, outputPath, enforceRelative) { : append; } +/** + * + * @param {string | function} value + * @returns {string} + */ +function stringifyLocal(value) { + return typeof value === "function" ? value.toString() : JSON.stringify(value); +} + +/** + * + * @param {{ [key: string]: string | function }} object + * @returns {string} + */ +function stringifyLocals(object) { + return `{${Object.entries(object) + .map(([key, value]) => `${JSON.stringify(key)}:${stringifyLocal(value)}`) + .join(",")}}`; +} + module.exports = { trueFn, findModuleById, @@ -216,5 +236,7 @@ module.exports = { BASE_URI, SINGLE_DOT_PATH_SEGMENT, stringifyRequest, + stringifyLocal, + stringifyLocals, getUndoPath, };