plugins.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. // ------------------------------------
  2. // # POSTCSS - LOAD PLUGINS - PLUGINS
  3. // ------------------------------------
  4. 'use strict'
  5. /**
  6. * @method plugins
  7. *
  8. * @param {Object} config PostCSS Config
  9. *
  10. * @return {Array} plugins PostCSS Plugins
  11. */
  12. module.exports = function plugins (config) {
  13. var plugins = []
  14. if (Array.isArray(config.plugins)) {
  15. plugins = config.plugins.filter(Boolean)
  16. if (plugins.length && plugins.length > 0) {
  17. plugins.forEach(function (plugin, i) {
  18. if (!plugin) throw new Error('Loading PostCSS Plugin failed')
  19. if (plugin.postcss) plugin = plugin.postcss
  20. if (plugin.default) plugin = plugin.default
  21. if (
  22. !(typeof plugin === 'object' && Array.isArray(plugin.plugins) ||
  23. typeof plugin === 'function')
  24. ) {
  25. throw new TypeError('Invalid PostCSS Plugin found: ' + '[' + i + ']')
  26. }
  27. })
  28. }
  29. return plugins
  30. } else {
  31. config = config.plugins
  32. var load = function (plugin, options) {
  33. if (options === null || Object.keys(options).length === 0) {
  34. try {
  35. return require(plugin)
  36. } catch (err) {
  37. err.message = 'Loading PostCSS Plugin failed: ' + err.message
  38. throw err
  39. }
  40. } else {
  41. try {
  42. return require(plugin)(options)
  43. } catch (err) {
  44. err.message = 'Loading PostCSS Plugin failed: ' + err.message
  45. throw err
  46. }
  47. }
  48. }
  49. Object.keys(config)
  50. .filter(function (plugin) {
  51. return config[plugin] !== false ? plugin : ''
  52. })
  53. .forEach(function (plugin, i) {
  54. plugin = load(plugin, config[plugin])
  55. if (plugin.postcss) plugin = plugin.postcss
  56. if (plugin.default) plugin = plugin.default
  57. if (
  58. !(typeof plugin === 'object' && Array.isArray(plugin.plugins) ||
  59. typeof plugin === 'function')
  60. ) {
  61. throw new TypeError('Invalid PostCSS Plugin found: ' + '[' + i + ']')
  62. }
  63. return plugins.push(plugin)
  64. })
  65. return plugins
  66. }
  67. }