-
-
Save lahmatiy/d68e91a507cc03f76eafab75a3d81582 to your computer and use it in GitHub Desktop.
Naive solution to get a list of all included CSS Modules
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
const { resolve, dirname } = require('path'); | |
const matchExtensions = /\.css$/i; | |
module.exports = function({ types: t }) { | |
return { | |
visitor: { | |
// import styles from './style.css'; | |
ImportDefaultSpecifier(path) { | |
const { value } = path.parentPath.node.source; | |
if (matchExtensions.test(value)) { | |
const { name } = path.node.local; | |
const { parentPath } = path; | |
path.remove(); | |
parentPath.replaceWith(t.variableDeclaration('const', [ | |
t.variableDeclarator( | |
t.identifier(name), | |
t.callExpression(t.identifier('require'), [t.stringLiteral(value)]) | |
) | |
])); | |
} | |
}, | |
// const styles = require('./styles.css'); | |
CallExpression(path, { file }) { | |
const { callee: { name: calleeName }, arguments: args } = path.node; | |
if (calleeName !== 'require' || !args.length || !t.isStringLiteral(args[0])) { | |
return; | |
} | |
const [{ value: stylesheetPath }] = args; | |
if (matchExtensions.test(stylesheetPath)) { | |
let csspath = resolve('node_modules/' + stylesheetPath); | |
if (stylesheetPath[0] === '.') { | |
const requiringFile = file.opts.filename; | |
csspath = resolve(dirname(requiringFile), stylesheetPath); | |
} | |
const tokens = require(csspath) || {}; | |
if (!t.isExpressionStatement(path.parent)) { | |
path.replaceWithSourceString(` | |
(function(){ | |
global.includedCssModules = global.includedCssModules || []; | |
if (global.includedCssModules.indexOf('${csspath}') === -1) { | |
global.includedCssModules.push('${csspath}'); | |
} | |
return ${JSON.stringify(tokens)}; | |
})() | |
`); | |
} else { | |
csspath.remove(); | |
} | |
} | |
} | |
} | |
}; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment