Skip to content

Instantly share code, notes, and snippets.

@joeybaker
Last active November 17, 2016 02:59
Show Gist options
  • Save joeybaker/a99b909f333eefbc2bea to your computer and use it in GitHub Desktop.
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
import setupCSS from './load-css-require.js'
setupCSS(__dirname, (err) => {
if (err) throw err
require('my-front-end-components-that-require-css-files.js')
})
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