scss-compiler.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. const path = require('path')
  2. const fs = require('fs')
  3. const ensureRequire = require('../ensure-require')
  4. const getVueJestConfig = require('../get-vue-jest-config')
  5. const logger = require('../logger')
  6. const applyModuleNameMapper = require('./helpers/module-name-mapper-helper')
  7. /**
  8. * This module is meant to compile scss
  9. *
  10. * @param {String} content - the content of the scss string that should be compiled
  11. * @param {String} filePath - the path of the file holding the scss
  12. * @param {Object} jestConfig - the complete jest config
  13. * @returns {String} styles - the compiled scss
  14. */
  15. module.exports = (content, filePath, jestConfig = {}) => {
  16. const vueJestConfig = getVueJestConfig(jestConfig)
  17. ensureRequire('scss', ['node-sass'])
  18. const sass = require('node-sass')
  19. let scssResources = ''
  20. if (vueJestConfig.resources && vueJestConfig.resources.scss) {
  21. scssResources = vueJestConfig.resources.scss
  22. .map(scssResource => path.resolve(process.cwd(), scssResource))
  23. .filter(scssResourcePath => fs.existsSync(scssResourcePath))
  24. .map(scssResourcePath => fs.readFileSync(scssResourcePath).toString())
  25. .join('\n')
  26. }
  27. try {
  28. return sass.renderSync({
  29. data: scssResources + content,
  30. outputStyle: 'compressed',
  31. importer: (url, prev, done) => ({ file: applyModuleNameMapper(url, prev === 'stdin' ? filePath : prev, jestConfig) })
  32. }).css.toString()
  33. } catch (err) {
  34. if (!vueJestConfig.hideStyleWarn) {
  35. logger.warn(`There was an error rendering the SCSS in ${filePath}. SCSS is fully supported by vue-jest. Still some features might throw errors. Webpack aliases are a common cause of errors. If you use Webpack aliases, please use jest's suggested way via moduleNameMapper which is supported.`)
  36. logger.warn(`Error while compiling styles: ${err}`)
  37. }
  38. }
  39. return ''
  40. }