Skip to content

Commit db5d1be

Browse files
committed
feat(loader): add functions support for locals
1 parent 866abbe commit db5d1be

File tree

2 files changed

+31
-6
lines changed

2 files changed

+31
-6
lines changed

src/loader.js

+9-6
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,8 @@ const {
88
BASE_URI,
99
SINGLE_DOT_PATH_SEGMENT,
1010
stringifyRequest,
11+
stringifyLocals,
12+
stringifyLocal,
1113
} = require("./utils");
1214
const schema = require("./loader-options.json");
1315

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

3941
/**
4042
* @param {string} content
41-
* @param {{ loaderContext: import("webpack").LoaderContext<LoaderOptions>, options: LoaderOptions, locals: {[key: string]: string } | undefined }} context
43+
* @param {{ loaderContext: import("webpack").LoaderContext<LoaderOptions>, options: LoaderOptions, locals: { [key: string]: string | function } | undefined }} context
4244
* @returns {string}
4345
*/
4446
function hotLoader(content, context) {
@@ -95,7 +97,7 @@ function pitch(request) {
9597
* @returns {void}
9698
*/
9799
const handleExports = (originalExports, compilation, assets, assetsInfo) => {
98-
/** @type {{[key: string]: string } | undefined} */
100+
/** @type {{[key: string]: string | function } | undefined} */
99101
let locals;
100102
let namedExport;
101103

@@ -228,15 +230,16 @@ function pitch(request) {
228230
? Object.keys(locals)
229231
.map(
230232
(key) =>
231-
`\nexport var ${key} = ${JSON.stringify(
232-
/** @type {{[key: string]: string }} */
233-
(locals)[key]
233+
`\nexport var ${key} = ${stringifyLocal(
234+
/** @type {{ [key: string]: string | function }} */ (locals)[
235+
key
236+
]
234237
)};`
235238
)
236239
.join("")
237240
: `\n${
238241
esModule ? "export default" : "module.exports ="
239-
} ${JSON.stringify(locals)};`
242+
} ${stringifyLocals(locals)};`
240243
: esModule
241244
? `\nexport {};`
242245
: "";

src/utils.js

+22
Original file line numberDiff line numberDiff line change
@@ -205,6 +205,26 @@ function getUndoPath(filename, outputPath, enforceRelative) {
205205
: append;
206206
}
207207

208+
/**
209+
*
210+
* @param {string | function} value
211+
* @returns {string}
212+
*/
213+
function stringifyLocal(value) {
214+
return typeof value === "function" ? value.toString() : JSON.stringify(value);
215+
}
216+
217+
/**
218+
*
219+
* @param {{ [key: string]: string | function }} object
220+
* @returns {string}
221+
*/
222+
function stringifyLocals(object) {
223+
return `{${Object.entries(object)
224+
.map(([key, value]) => `${JSON.stringify(key)}:${stringifyLocal(value)}`)
225+
.join(",")}}`;
226+
}
227+
208228
module.exports = {
209229
trueFn,
210230
findModuleById,
@@ -216,5 +236,7 @@ module.exports = {
216236
BASE_URI,
217237
SINGLE_DOT_PATH_SEGMENT,
218238
stringifyRequest,
239+
stringifyLocal,
240+
stringifyLocals,
219241
getUndoPath,
220242
};

0 commit comments

Comments
 (0)