Last active
November 17, 2016 02:59
-
-
Save joeybaker/a99b909f333eefbc2bea to your computer and use it in GitHub Desktop.
css-modules require hook for node. via https://github.com/css-modules/css-modules/issues/13
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import setupCSS from './load-css-require.js' | |
setupCSS(__dirname, (err) => { | |
if (err) throw err | |
require('my-front-end-components-that-require-css-files.js') | |
}) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import glob from 'glob' | |
import CSSLoader from 'css-modules-loader-core/lib/file-system-loader' | |
import path from 'path' | |
import async from 'async' | |
const EXT = '.css' | |
const getTokensForFile = (file, callback) => { | |
// via: https://github.com/css-modules/css-modulesify/blob/abe3c8ae214ca9c690c6b1622345688affc78d17/index.js#L86-L103 | |
const loader = new CSSLoader(path.dirname(file)) | |
loader.fetch(path.basename(file), '/') | |
.then((tokens) => { | |
callback(null, tokens) | |
}) | |
.catch(callback) | |
} | |
const enableCssRequireForFiles = (files, callback) => { | |
const tokenMap = require.extensions[EXT] && require.extensions[EXT].tokenMap || new Map() | |
// hack require so that css files can be required | |
require.extensions[EXT] = (module, file) => { | |
module.exports = tokenMap.get(file) | |
} | |
require.extensions[EXT].tokenMap = tokenMap | |
async.map(files, getTokensForFile, (err, tokensForFiles) => { | |
if (err) return void callback(err) | |
tokensForFiles.forEach((tokensForFile, i) => { | |
tokenMap.set(files[i], tokensForFile) | |
}) | |
callback() | |
}) | |
} | |
export default (componentDir, callback) => { | |
glob(path.join(componentDir, `**/*${EXT}`) | |
// we don't need to sort, just go | |
, {nosort: true} | |
, (err, files) => { | |
if (err) callback(err) | |
else enableCssRequireForFiles(files, callback) | |
} | |
) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment