Skip to content

Commit 5faa7a4

Browse files
lukeedegoist
authored andcommitted
Allow custom modules.getJSON function (#132)
Hey~! As of now, there's no way to access the JSON file of classnames to their outputs. It can only happen thru the [`getJSON` method of `postcss-modules`](https://github.com/css-modules/postcss-modules#saving-exported-classes), but it's overridden here. This PR allows a user to define a custom `getJSON` method, passing it all arguments for them to do as they please. It does not affect the core behavior of the plugin. --- _Also closes #101_
1 parent 59fb0e9 commit 5faa7a4

3 files changed

Lines changed: 53 additions & 1 deletion

File tree

src/postcss-loader.js

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -83,8 +83,11 @@ export default {
8383
'[name]_[local]' :
8484
'[name]_[local]__[hash:base64:5]',
8585
...options.modules,
86-
getJSON(filepath, json) {
86+
getJSON(filepath, json, outpath) {
8787
modulesExported[filepath] = json
88+
if (typeof options.modules === 'object' && typeof options.modules.getJSON === 'function') {
89+
return options.modules.getJSON(filepath, json, outpath)
90+
}
8891
}
8992
})
9093
)

test/__snapshots__/index.test.js.snap

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -540,6 +540,44 @@ console.log(style.foo);
540540
"
541541
`;
542542

543+
exports[`modules inject-object: js code 1`] = `
544+
"'use strict';
545+
546+
function styleInject(css, ref) {
547+
if ( ref === void 0 ) ref = {};
548+
var insertAt = ref.insertAt;
549+
550+
if (!css || typeof document === 'undefined') { return; }
551+
552+
var head = document.head || document.getElementsByTagName('head')[0];
553+
var style = document.createElement('style');
554+
style.type = 'text/css';
555+
556+
if (insertAt === 'top') {
557+
if (head.firstChild) {
558+
head.insertBefore(style, head.firstChild);
559+
} else {
560+
head.appendChild(style);
561+
}
562+
} else {
563+
head.appendChild(style);
564+
}
565+
566+
if (style.styleSheet) {
567+
style.styleSheet.cssText = css;
568+
} else {
569+
style.appendChild(document.createTextNode(css));
570+
}
571+
}
572+
573+
var css = \\".style_foo {\\\\n color: red;\\\\n}\\\\n\\";
574+
var style = {\\"foo\\":\\"style_foo\\"};
575+
styleInject(css);
576+
577+
console.log(style.foo);
578+
"
579+
`;
580+
543581
exports[`modules named-exports: js code 1`] = `
544582
"'use strict';
545583

test/index.test.js

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -163,6 +163,17 @@ snapshotMany('modules', [
163163
modules: true
164164
}
165165
},
166+
{
167+
title: 'inject-object',
168+
input: 'css-modules/index.js',
169+
options: {
170+
modules: {
171+
getJSON() {
172+
//
173+
}
174+
}
175+
}
176+
},
166177
{
167178
title: 'named-exports',
168179
input: 'named-exports/index.js',

0 commit comments

Comments
 (0)