processor.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. 'use strict'
  2. let NoWorkResult = require('./no-work-result')
  3. let LazyResult = require('./lazy-result')
  4. let Document = require('./document')
  5. let Root = require('./root')
  6. class Processor {
  7. constructor(plugins = []) {
  8. this.version = '8.4.27'
  9. this.plugins = this.normalize(plugins)
  10. }
  11. normalize(plugins) {
  12. let normalized = []
  13. for (let i of plugins) {
  14. if (i.postcss === true) {
  15. i = i()
  16. } else if (i.postcss) {
  17. i = i.postcss
  18. }
  19. if (typeof i === 'object' && Array.isArray(i.plugins)) {
  20. normalized = normalized.concat(i.plugins)
  21. } else if (typeof i === 'object' && i.postcssPlugin) {
  22. normalized.push(i)
  23. } else if (typeof i === 'function') {
  24. normalized.push(i)
  25. } else if (typeof i === 'object' && (i.parse || i.stringify)) {
  26. if (process.env.NODE_ENV !== 'production') {
  27. throw new Error(
  28. 'PostCSS syntaxes cannot be used as plugins. Instead, please use ' +
  29. 'one of the syntax/parser/stringifier options as outlined ' +
  30. 'in your PostCSS runner documentation.'
  31. )
  32. }
  33. } else {
  34. throw new Error(i + ' is not a PostCSS plugin')
  35. }
  36. }
  37. return normalized
  38. }
  39. process(css, opts = {}) {
  40. if (
  41. this.plugins.length === 0 &&
  42. typeof opts.parser === 'undefined' &&
  43. typeof opts.stringifier === 'undefined' &&
  44. typeof opts.syntax === 'undefined'
  45. ) {
  46. return new NoWorkResult(this, css, opts)
  47. } else {
  48. return new LazyResult(this, css, opts)
  49. }
  50. }
  51. use(plugin) {
  52. this.plugins = this.plugins.concat(this.normalize([plugin]))
  53. return this
  54. }
  55. }
  56. module.exports = Processor
  57. Processor.default = Processor
  58. Root.registerProcessor(Processor)
  59. Document.registerProcessor(Processor)