From d7f6ddb38f9254b5e6a90629d40738dfc484badc 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 | 18 +++++++++++------- src/utils.js | 10 ++++++++++ 2 files changed, 21 insertions(+), 7 deletions(-) diff --git a/src/loader.js b/src/loader.js index 6de4e3d6..423a14f4 100644 --- a/src/loader.js +++ b/src/loader.js @@ -8,6 +8,7 @@ const { BASE_URI, SINGLE_DOT_PATH_SEGMENT, stringifyRequest, + stringifyLocal, } = require("./utils"); const schema = require("./loader-options.json"); @@ -22,6 +23,7 @@ const MiniCssExtractPlugin = require("./index"); /** @typedef {import("webpack").AssetInfo} AssetInfo */ /** @typedef {import("webpack").NormalModule} NormalModule */ /** @typedef {import("./index.js").LoaderOptions} LoaderOptions */ +/** @typedef {{ [key: string]: string | function } | function} Locals */ /** @typedef {any} TODO */ @@ -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: Locals | 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 {Locals | undefined} */ let locals; let namedExport; @@ -170,7 +172,8 @@ function pitch(request) { locals = {}; } - locals[key] = originalExports[key]; + /** @type {{ [key: string]: string }} */ (locals)[key] = + originalExports[key]; } }); } else { @@ -228,15 +231,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)};` + } ${stringifyLocal(/** @type {function} */ (locals))};` : esModule ? `\nexport {};` : ""; diff --git a/src/utils.js b/src/utils.js index 416b38c1..68ab5f08 100644 --- a/src/utils.js +++ b/src/utils.js @@ -205,6 +205,15 @@ function getUndoPath(filename, outputPath, enforceRelative) { : append; } +/** + * + * @param {string | function} value + * @returns {string} + */ +function stringifyLocal(value) { + return typeof value === "function" ? value.toString() : JSON.stringify(value); +} + module.exports = { trueFn, findModuleById, @@ -216,5 +225,6 @@ module.exports = { BASE_URI, SINGLE_DOT_PATH_SEGMENT, stringifyRequest, + stringifyLocal, getUndoPath, };