processor.js 2.1 KB

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