|
| 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 | + |
| 9 | +let prevCheckIsAsync = null |
| 10 | +function hasAsyncPlugin () { |
| 11 | + if (prevCheckIsAsync !== null) { |
| 12 | + return prevCheckIsAsync |
| 13 | + } |
| 14 | + const result = postcss(plugins) |
| 15 | + .process('', { |
| 16 | + from: undefined |
| 17 | + }) |
| 18 | + |
| 19 | + if (result.processing) { |
| 20 | + prevCheckIsAsync = true |
| 21 | + return prevCheckIsAsync |
| 22 | + } |
| 23 | + for (const plugin of result.processor.plugins) { |
| 24 | + const promise = result.run(plugin) |
| 25 | + if (typeof promise === 'object' && typeof promise.then === 'function') { |
| 26 | + prevCheckIsAsync = true |
| 27 | + break |
| 28 | + } |
| 29 | + } |
| 30 | + if (prevCheckIsAsync === null) { |
| 31 | + prevCheckIsAsync = false |
| 32 | + } |
| 33 | + |
| 34 | + return prevCheckIsAsync |
| 35 | +} |
| 36 | + |
| 37 | +function catchError (error, filePath, jestConfig) { |
| 38 | + if (!getVueJestConfig(jestConfig).hideStyleWarn) { |
| 39 | + logger.warn(`There was an error rendering the POSTCSS in ${filePath}. `) |
| 40 | + logger.warn(`Error while compiling styles: ${error}`) |
| 41 | + } |
| 42 | +} |
| 43 | + |
| 44 | +module.exports = (content, filePath, jestConfig) => { |
| 45 | + ensureRequire('postcss', ['postcss']) |
| 46 | + |
| 47 | + let css = null |
| 48 | + |
| 49 | + const res = postcss(plugins) |
| 50 | + .process(content, { |
| 51 | + from: undefined |
| 52 | + }) |
| 53 | + |
| 54 | + if (hasAsyncPlugin()) { |
| 55 | + res |
| 56 | + .then(result => { |
| 57 | + css = result.css || '' |
| 58 | + }) |
| 59 | + .catch((e) => { |
| 60 | + css = '' |
| 61 | + catchError(e, filePath, jestConfig) |
| 62 | + }) |
| 63 | + |
| 64 | + while (css === null) { //eslint-disable-line |
| 65 | + require('deasync').sleep(100) |
| 66 | + } |
| 67 | + |
| 68 | + return css |
| 69 | + } |
| 70 | + |
| 71 | + try { |
| 72 | + return res.css |
| 73 | + } catch (e) { |
| 74 | + catchError(e, filePath, jestConfig) |
| 75 | + return '' |
| 76 | + } |
| 77 | +} |
0 commit comments