Skip to content

Commit

Permalink
feat(loader): add functions support for locals
Browse files Browse the repository at this point in the history
  • Loading branch information
yungvldai committed Oct 24, 2022
1 parent 866abbe commit db5d1be
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 6 deletions.
15 changes: 9 additions & 6 deletions src/loader.js
Expand Up @@ -8,6 +8,8 @@ const {
BASE_URI,
SINGLE_DOT_PATH_SEGMENT,
stringifyRequest,
stringifyLocals,
stringifyLocal,
} = require("./utils");
const schema = require("./loader-options.json");

Expand Down Expand Up @@ -38,7 +40,7 @@ const MiniCssExtractPlugin = require("./index");

/**
* @param {string} content
* @param {{ loaderContext: import("webpack").LoaderContext<LoaderOptions>, options: LoaderOptions, locals: {[key: string]: string } | undefined }} context
* @param {{ loaderContext: import("webpack").LoaderContext<LoaderOptions>, options: LoaderOptions, locals: { [key: string]: string | function } | undefined }} context
* @returns {string}
*/
function hotLoader(content, context) {
Expand Down Expand Up @@ -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;

Expand Down Expand Up @@ -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 {};`
: "";
Expand Down
22 changes: 22 additions & 0 deletions src/utils.js
Expand Up @@ -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,
Expand All @@ -216,5 +236,7 @@ module.exports = {
BASE_URI,
SINGLE_DOT_PATH_SEGMENT,
stringifyRequest,
stringifyLocal,
stringifyLocals,
getUndoPath,
};

0 comments on commit db5d1be

Please sign in to comment.