index.js 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. 'use strict';
  2. const browserslist = require('browserslist');
  3. const plugins = require('./plugins');
  4. /** @typedef {{lint?: boolean}} Options */
  5. /**
  6. * @type {import('postcss').PluginCreator<Options>}
  7. * @param {Options} opts
  8. * @return {import('postcss').Plugin}
  9. */
  10. function pluginCreator(opts = {}) {
  11. return {
  12. postcssPlugin: 'stylehacks',
  13. OnceExit(css, { result }) {
  14. /** @type {typeof result.opts & browserslist.Options} */
  15. const resultOpts = result.opts || {};
  16. const browsers = browserslist(null, {
  17. stats: resultOpts.stats,
  18. path: __dirname,
  19. env: resultOpts.env,
  20. });
  21. /** @type {import('./plugin').Plugin[]} */
  22. const processors = [];
  23. for (const Plugin of plugins) {
  24. const hack = new Plugin(result);
  25. if (!browsers.some((browser) => hack.targets.has(browser))) {
  26. processors.push(hack);
  27. }
  28. }
  29. css.walk((node) => {
  30. processors.forEach((proc) => {
  31. if (!proc.nodeTypes.has(node.type)) {
  32. return;
  33. }
  34. if (opts.lint) {
  35. return proc.detectAndWarn(node);
  36. }
  37. return proc.detectAndResolve(node);
  38. });
  39. });
  40. },
  41. };
  42. }
  43. /** @type {(node: import('postcss').Node) => boolean} */
  44. pluginCreator.detect = (node) => {
  45. return plugins.some((Plugin) => {
  46. const hack = new Plugin();
  47. return hack.any(node);
  48. });
  49. };
  50. pluginCreator.postcss = true;
  51. module.exports = pluginCreator;