configTransforms.js 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. const extendJSConfig = require('./extendJSConfig')
  2. const stringifyJS = require('./stringifyJS')
  3. const { loadModule } = require('@vue/cli-shared-utils')
  4. const merge = require('deepmerge')
  5. const mergeArrayWithDedupe = (a, b) => Array.from(new Set([...a, ...b]))
  6. const mergeOptions = {
  7. arrayMerge: mergeArrayWithDedupe
  8. }
  9. const isObject = val => val && typeof val === 'object'
  10. const transformJS = {
  11. read: ({ filename, context }) => {
  12. try {
  13. return loadModule(`./${filename}`, context, true)
  14. } catch (e) {
  15. return null
  16. }
  17. },
  18. write: ({ value, existing, source }) => {
  19. if (existing) {
  20. // We merge only the modified keys
  21. const changedData = {}
  22. Object.keys(value).forEach(key => {
  23. const originalValue = existing[key]
  24. const newValue = value[key]
  25. if (Array.isArray(originalValue) && Array.isArray(newValue)) {
  26. changedData[key] = mergeArrayWithDedupe(originalValue, newValue)
  27. } else if (isObject(originalValue) && isObject(newValue)) {
  28. changedData[key] = merge(originalValue, newValue, mergeOptions)
  29. } else {
  30. changedData[key] = newValue
  31. }
  32. })
  33. return extendJSConfig(changedData, source)
  34. } else {
  35. return `module.exports = ${stringifyJS(value, null, 2)}`
  36. }
  37. }
  38. }
  39. const transformJSON = {
  40. read: ({ source }) => JSON.parse(source),
  41. write: ({ value, existing }) => {
  42. return JSON.stringify(merge(existing, value, mergeOptions), null, 2)
  43. }
  44. }
  45. const transformYAML = {
  46. read: ({ source }) => require('js-yaml').safeLoad(source),
  47. write: ({ value, existing }) => {
  48. return require('js-yaml').safeDump(merge(existing, value, mergeOptions), {
  49. skipInvalid: true
  50. })
  51. }
  52. }
  53. const transformLines = {
  54. read: ({ source }) => source.split('\n'),
  55. write: ({ value, existing }) => {
  56. if (existing) {
  57. value = existing.concat(value)
  58. // Dedupe
  59. value = value.filter((item, index) => value.indexOf(item) === index)
  60. }
  61. return value.join('\n')
  62. }
  63. }
  64. module.exports = {
  65. js: transformJS,
  66. json: transformJSON,
  67. yaml: transformYAML,
  68. lines: transformLines
  69. }