Skip to content

Instantly share code, notes, and snippets.

@lahmatiy
Created December 10, 2017 14:49
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lahmatiy/d68e91a507cc03f76eafab75a3d81582 to your computer and use it in GitHub Desktop.
Save lahmatiy/d68e91a507cc03f76eafab75a3d81582 to your computer and use it in GitHub Desktop.
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