postcss-compiler.js 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. const postcss = require('postcss')
  2. const postcssrc = require('postcss-load-config')
  3. const ctx = { parser: true, map: 'inline' }
  4. const { plugins } = postcssrc.sync(ctx)
  5. const logger = require('../logger')
  6. const getVueJestConfig = require('../get-vue-jest-config')
  7. const ensureRequire = require('../ensure-require')
  8. let prevCheckIsAsync = null
  9. function hasAsyncPlugin () {
  10. if (prevCheckIsAsync !== null) {
  11. return prevCheckIsAsync
  12. }
  13. const result = postcss(plugins)
  14. .process('', {
  15. from: undefined
  16. })
  17. if (result.processing) {
  18. prevCheckIsAsync = true
  19. return prevCheckIsAsync
  20. }
  21. for (const plugin of result.processor.plugins) {
  22. const promise = result.run(plugin)
  23. if (typeof promise === 'object' && typeof promise.then === 'function') {
  24. prevCheckIsAsync = true
  25. break
  26. }
  27. }
  28. if (prevCheckIsAsync === null) {
  29. prevCheckIsAsync = false
  30. }
  31. return prevCheckIsAsync
  32. }
  33. function catchError (error, filePath, jestConfig) {
  34. if (!getVueJestConfig(jestConfig).hideStyleWarn) {
  35. logger.warn(`There was an error rendering the POSTCSS in ${filePath}. `)
  36. logger.warn(`Error while compiling styles: ${error}`)
  37. }
  38. }
  39. module.exports = (content, filePath, jestConfig) => {
  40. ensureRequire('postcss', ['postcss'])
  41. let css = null
  42. const res = postcss(plugins)
  43. .process(content, {
  44. from: undefined
  45. })
  46. if (hasAsyncPlugin()) {
  47. res
  48. .then(result => {
  49. css = result.css || ''
  50. })
  51. .catch((e) => {
  52. css = ''
  53. catchError(e, filePath, jestConfig)
  54. })
  55. while (css === null) { //eslint-disable-line
  56. require('deasync').sleep(100)
  57. }
  58. return css
  59. }
  60. try {
  61. return res.css
  62. } catch (e) {
  63. catchError(e, filePath, jestConfig)
  64. return ''
  65. }
  66. }