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 d7f6ddb
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 7 deletions.
18 changes: 11 additions & 7 deletions src/loader.js
Expand Up @@ -8,6 +8,7 @@ const {
BASE_URI,
SINGLE_DOT_PATH_SEGMENT,
stringifyRequest,
stringifyLocal,
} = require("./utils");
const schema = require("./loader-options.json");

Expand All @@ -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 */

Expand All @@ -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: Locals | 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 {Locals | undefined} */
let locals;
let namedExport;

Expand Down Expand Up @@ -170,7 +172,8 @@ function pitch(request) {
locals = {};
}

locals[key] = originalExports[key];
/** @type {{ [key: string]: string }} */ (locals)[key] =
originalExports[key];
}
});
} else {
Expand Down Expand Up @@ -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 {};`
: "";
Expand Down
10 changes: 10 additions & 0 deletions src/utils.js
Expand Up @@ -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,
Expand All @@ -216,5 +225,6 @@ module.exports = {
BASE_URI,
SINGLE_DOT_PATH_SEGMENT,
stringifyRequest,
stringifyLocal,
getUndoPath,
};

0 comments on commit d7f6ddb

Please sign in to comment.