Skip to content

Instantly share code, notes, and snippets.

@lahmatiy

lahmatiy/collect-styles-path.js Secret

Created Dec 10, 2017
Embed
What would you like to do?
Naive solution to get a list of all included CSS Modules
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