From 5faa7a4211ae8169b816a7e6b01c3feea4e6507c Mon Sep 17 00:00:00 2001 From: Luke Edwards Date: Tue, 22 Jan 2019 10:12:21 -0800 Subject: [PATCH] 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_ --- src/postcss-loader.js | 5 +++- test/__snapshots__/index.test.js.snap | 38 +++++++++++++++++++++++++++ test/index.test.js | 11 ++++++++ 3 files changed, 53 insertions(+), 1 deletion(-) diff --git a/src/postcss-loader.js b/src/postcss-loader.js index 6a790d57..974d68c8 100644 --- a/src/postcss-loader.js +++ b/src/postcss-loader.js @@ -83,8 +83,11 @@ export default { '[name]_[local]' : '[name]_[local]__[hash:base64:5]', ...options.modules, - getJSON(filepath, json) { + getJSON(filepath, json, outpath) { modulesExported[filepath] = json + if (typeof options.modules === 'object' && typeof options.modules.getJSON === 'function') { + return options.modules.getJSON(filepath, json, outpath) + } } }) ) diff --git a/test/__snapshots__/index.test.js.snap b/test/__snapshots__/index.test.js.snap index 14c7961d..e56ca9fe 100644 --- a/test/__snapshots__/index.test.js.snap +++ b/test/__snapshots__/index.test.js.snap @@ -540,6 +540,44 @@ console.log(style.foo); " `; +exports[`modules inject-object: js code 1`] = ` +"'use strict'; + +function styleInject(css, ref) { + if ( ref === void 0 ) ref = {}; + var insertAt = ref.insertAt; + + if (!css || typeof document === 'undefined') { return; } + + var head = document.head || document.getElementsByTagName('head')[0]; + var style = document.createElement('style'); + style.type = 'text/css'; + + if (insertAt === 'top') { + if (head.firstChild) { + head.insertBefore(style, head.firstChild); + } else { + head.appendChild(style); + } + } else { + head.appendChild(style); + } + + if (style.styleSheet) { + style.styleSheet.cssText = css; + } else { + style.appendChild(document.createTextNode(css)); + } +} + +var css = \\".style_foo {\\\\n color: red;\\\\n}\\\\n\\"; +var style = {\\"foo\\":\\"style_foo\\"}; +styleInject(css); + +console.log(style.foo); +" +`; + exports[`modules named-exports: js code 1`] = ` "'use strict'; diff --git a/test/index.test.js b/test/index.test.js index 8bb78586..0e4179a1 100644 --- a/test/index.test.js +++ b/test/index.test.js @@ -163,6 +163,17 @@ snapshotMany('modules', [ modules: true } }, + { + title: 'inject-object', + input: 'css-modules/index.js', + options: { + modules: { + getJSON() { + // + } + } + } + }, { title: 'named-exports', input: 'named-exports/index.js',