index.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. module.exports = function postcssPrefixSelector(options) {
  2. const prefix = options.prefix;
  3. const prefixWithSpace = /\s+$/.test(prefix) ? prefix : `${prefix} `;
  4. const ignoreFiles = options.ignoreFiles ? [].concat(options.ignoreFiles) : [];
  5. const includeFiles = options.includeFiles
  6. ? [].concat(options.includeFiles)
  7. : [];
  8. return function (root) {
  9. if (
  10. ignoreFiles.length &&
  11. root.source.input.file &&
  12. isFileInArray(root.source.input.file, ignoreFiles)
  13. ) {
  14. return;
  15. }
  16. if (
  17. includeFiles.length &&
  18. root.source.input.file &&
  19. !isFileInArray(root.source.input.file, includeFiles)
  20. ) {
  21. return;
  22. }
  23. root.walkRules((rule) => {
  24. const keyframeRules = [
  25. 'keyframes',
  26. '-webkit-keyframes',
  27. '-moz-keyframes',
  28. '-o-keyframes',
  29. ];
  30. if (rule.parent && keyframeRules.includes(rule.parent.name)) {
  31. return;
  32. }
  33. rule.selectors = rule.selectors.map((selector) => {
  34. if (options.exclude && excludeSelector(selector, options.exclude)) {
  35. return selector;
  36. }
  37. if (options.transform) {
  38. return options.transform(
  39. prefix,
  40. selector,
  41. prefixWithSpace + selector,
  42. root.source.input.file,
  43. rule
  44. );
  45. }
  46. return prefixWithSpace + selector;
  47. });
  48. });
  49. };
  50. };
  51. function isFileInArray(file, arr) {
  52. return arr.some((ruleOrString) => {
  53. if (ruleOrString instanceof RegExp) {
  54. return ruleOrString.test(file);
  55. }
  56. return file.includes(ruleOrString);
  57. });
  58. }
  59. function excludeSelector(selector, excludeArr) {
  60. return excludeArr.some((excludeRule) => {
  61. if (excludeRule instanceof RegExp) {
  62. return excludeRule.test(selector);
  63. }
  64. return selector === excludeRule;
  65. });
  66. }