addStylesServer.js 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. import listToStyles from './listToStyles'
  2. export default function addStylesServer (parentId, list, isProduction, context) {
  3. if (!context && typeof __VUE_SSR_CONTEXT__ !== 'undefined') {
  4. context = __VUE_SSR_CONTEXT__
  5. }
  6. if (context) {
  7. if (!context.hasOwnProperty('styles')) {
  8. Object.defineProperty(context, 'styles', {
  9. enumerable: true,
  10. get: function() {
  11. return renderStyles(context._styles)
  12. }
  13. })
  14. // expose renderStyles for vue-server-renderer (vuejs/#6353)
  15. context._renderStyles = renderStyles
  16. }
  17. var styles = context._styles || (context._styles = {})
  18. list = listToStyles(parentId, list)
  19. if (isProduction) {
  20. addStyleProd(styles, list)
  21. } else {
  22. addStyleDev(styles, list)
  23. }
  24. }
  25. }
  26. // In production, render as few style tags as possible.
  27. // (mostly because IE9 has a limit on number of style tags)
  28. function addStyleProd (styles, list) {
  29. for (var i = 0; i < list.length; i++) {
  30. var parts = list[i].parts
  31. for (var j = 0; j < parts.length; j++) {
  32. var part = parts[j]
  33. // group style tags by media types.
  34. var id = part.media || 'default'
  35. var style = styles[id]
  36. if (style) {
  37. if (style.ids.indexOf(part.id) < 0) {
  38. style.ids.push(part.id)
  39. style.css += '\n' + part.css
  40. }
  41. } else {
  42. styles[id] = {
  43. ids: [part.id],
  44. css: part.css,
  45. media: part.media
  46. }
  47. }
  48. }
  49. }
  50. }
  51. // In dev we use individual style tag for each module for hot-reload
  52. // and source maps.
  53. function addStyleDev (styles, list) {
  54. for (var i = 0; i < list.length; i++) {
  55. var parts = list[i].parts
  56. for (var j = 0; j < parts.length; j++) {
  57. var part = parts[j]
  58. styles[part.id] = {
  59. ids: [part.id],
  60. css: part.css,
  61. media: part.media
  62. }
  63. }
  64. }
  65. }
  66. function renderStyles (styles) {
  67. var css = ''
  68. for (var key in styles) {
  69. var style = styles[key]
  70. css += '<style data-vue-ssr-id="' + style.ids.join(' ') + '"' +
  71. (style.media ? ( ' media="' + style.media + '"' ) : '') + '>' +
  72. style.css + '</style>'
  73. }
  74. return css
  75. }