load-postcss-config.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. const load = require('postcss-load-config')
  2. let loaded
  3. function isObject (val) {
  4. return val && typeof val === 'object'
  5. }
  6. module.exports = function loadPostcssConfig (loaderContext, inlineConfig = {}) {
  7. if (inlineConfig.useConfigFile === false) {
  8. return Promise.resolve({
  9. plugins: inlineConfig.plugins || [],
  10. options: inlineConfig.options || {}
  11. })
  12. }
  13. if (process.env.VUE_LOADER_TEST || !loaded) {
  14. const config = inlineConfig.config || {}
  15. const ctx = { webpack: loaderContext }
  16. if (config.ctx) {
  17. ctx.options = config.ctx
  18. }
  19. loaded = load(ctx, config.path, { argv: false }).catch(err => {
  20. // postcss-load-config throws error when no config file is found,
  21. // but for us it's optional. only emit other errors
  22. if (err.message.indexOf('No PostCSS Config found') >= 0) {
  23. return
  24. }
  25. const friendlyErr = new Error(`Error loading PostCSS config: ${err.message}`)
  26. Error.captureStackTrace(friendlyErr, err)
  27. loaderContext.emitError(friendlyErr)
  28. })
  29. }
  30. return loaded.then(config => {
  31. let plugins = []
  32. let options = {}
  33. // inline postcss options for vue-loader
  34. if (typeof inlineConfig === 'function') {
  35. inlineConfig = inlineConfig.call(this, this)
  36. }
  37. if (Array.isArray(inlineConfig)) {
  38. plugins = inlineConfig
  39. } else if (isObject(inlineConfig)) {
  40. plugins =
  41. typeof inlineConfig.plugins === 'function'
  42. ? inlineConfig.plugins.call(this, this)
  43. : inlineConfig.plugins || []
  44. options = inlineConfig.options || {}
  45. }
  46. // merge postcss config file
  47. if (config && config.plugins) {
  48. plugins = plugins.concat(config.plugins)
  49. }
  50. if (config && config.options) {
  51. options = Object.assign({}, config.options, options)
  52. }
  53. return {
  54. plugins,
  55. options
  56. }
  57. })
  58. }