From eeb72f7506711a4e9c4161c5842441d6121343c4 Mon Sep 17 00:00:00 2001 From: Izaak Schroeder Date: Fri, 19 May 2017 17:00:32 -0700 Subject: [PATCH] Add server-side CSS module hook. If you're using this loader on the server-side without doing webpack server side transforms you can use this hook to rewrite a module's exports to its equivalent CSS identifier. Because of how webpack works you will need to provide the context and local identifier name that was used to build the client-side CSS (typically `process.cwd()` is enough for the context). Example usage: ```javascript var css = require('css-js-loader/register'); css(process.cwd(), '[hash:base64]'); ``` Note that I particularly don't condone this kind of thing (especially mucking about hooking node internals), but not all environments support server-side webpack either due to political or technical reasons so this will at least allow those users to play with this package. --- register.js | 24 ++++++++++++++++++++++++ rewrite.js | 15 +++++++++++++++ 2 files changed, 39 insertions(+) create mode 100644 register.js create mode 100644 rewrite.js diff --git a/register.js b/register.js new file mode 100644 index 0000000..ba99daa --- /dev/null +++ b/register.js @@ -0,0 +1,24 @@ +var Module = require('module'); + +function register(context, localIdentName) { + function f(_, r, m, __filename) { + var q = __WRAPPED__; + q.apply(this, arguments); + if (/\.css\.js$/.exec(__filename)) { + r('__REWRITE__')(__CONTEXT__, __IDENT_NAME__, m); + } + } + + var oldWrap = Module.wrap; + var body = '(' + f.toString() + ')'; + body = body.replace(/__REWRITE__/, require.resolve('./rewrite')); + body = body.replace(/__CONTEXT__/, JSON.stringify(context)); + body = body.replace(/__IDENT_NAME__/, JSON.stringify(localIdentName)); + Module.wrap = function webpackPolyfill(content) { + return body.replace(/__WRAPPED__/, function() { + return oldWrap(content); + }); + }; +} + +module.exports = register; diff --git a/rewrite.js b/rewrite.js new file mode 100644 index 0000000..48954df --- /dev/null +++ b/rewrite.js @@ -0,0 +1,15 @@ +/* eslint-disable guard-for-in */ + +var path = require('path'); +var getLocalIdent = require('css-loader/lib/getLocalIdent'); + +module.exports = function(context, localIdentName, module) { + for (var key in module.exports) { + module.exports[key] = getLocalIdent( + {resourcePath: module.filename}, + localIdentName, + key, + {context: context, hashPrefix: ''} + ); + } +};