Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -23,5 +23,7 @@
"@types/webpack": "^4.4.24",
"typescript": "^3.3.1"
},
"dependencies": {}
"dependencies": {
"css-tree": "^1.0.0-alpha.33"
}
}
26 changes: 14 additions & 12 deletions src/style-loader.ts
Original file line number Diff line number Diff line change
@@ -1,21 +1,23 @@
import csstree from 'css-tree';
import { createDirHash } from './lib/dirhash';
import { LoaderContext } from './options';

export default function styleLoader(this: LoaderContext, source: string): string {
const { globalsPrefix = 'app' } = this.query;
const [dirName, dirHash] = createDirHash(this.context);
const ast = csstree.parse(source);

const classLineRegex = /(.*(\..*?)(?<!;)$)/gm;
const classRegex = new RegExp(`(?<=\\.)((?!${globalsPrefix}-)\\w+[\\w-]*\\b)`, 'g');

if (!source.match(classLineRegex)) {
return source;
}
csstree.walk(ast, {
visit: 'ClassSelector',
enter: function(node) {
const className = node.name

const [dirName, dirHash] = createDirHash(this.context);
if (className.startsWith(globalsPrefix)) return;
node.name = `${dirName}-${dirHash}-${className}`;
}
});

return source.replace(classLineRegex, matchingLine =>
matchingLine.replace(classRegex, className =>
`${dirName}-${dirHash}-${className}`
)
);
return csstree.generate(ast, {
sourceMap: false // if true, returns object instead of string
});
};