client-plugin.js 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148
  1. 'use strict';
  2. Object.freeze({});
  3. /**
  4. * Make a map and return a function for checking if a key
  5. * is in that map.
  6. */
  7. function makeMap(str, expectsLowerCase) {
  8. const map = Object.create(null);
  9. const list = str.split(',');
  10. for (let i = 0; i < list.length; i++) {
  11. map[list[i]] = true;
  12. }
  13. return expectsLowerCase ? val => map[val.toLowerCase()] : val => map[val];
  14. }
  15. /**
  16. * Check if a tag is a built-in tag.
  17. */
  18. makeMap('slot,component', true);
  19. /**
  20. * Check if an attribute is a reserved attribute.
  21. */
  22. makeMap('key,ref,slot,slot-scope,is');
  23. makeMap('accept,accept-charset,accesskey,action,align,alt,async,autocomplete,' +
  24. 'autofocus,autoplay,autosave,bgcolor,border,buffered,challenge,charset,' +
  25. 'checked,cite,class,code,codebase,color,cols,colspan,content,' +
  26. 'contenteditable,contextmenu,controls,coords,data,datetime,default,' +
  27. 'defer,dir,dirname,disabled,download,draggable,dropzone,enctype,for,' +
  28. 'form,formaction,headers,height,hidden,high,href,hreflang,http-equiv,' +
  29. 'icon,id,ismap,itemprop,keytype,kind,label,lang,language,list,loop,low,' +
  30. 'manifest,max,maxlength,media,method,GET,POST,min,multiple,email,file,' +
  31. 'muted,name,novalidate,open,optimum,pattern,ping,placeholder,poster,' +
  32. 'preload,radiogroup,readonly,rel,required,reversed,rows,rowspan,sandbox,' +
  33. 'scope,scoped,seamless,selected,shape,size,type,text,password,sizes,span,' +
  34. 'spellcheck,src,srcdoc,srclang,srcset,start,step,style,summary,tabindex,' +
  35. 'target,title,usemap,value,width,wrap');
  36. const isJS = (file) => /\.js(\?[^.]+)?$/.test(file);
  37. const isCSS = (file) => /\.css(\?[^.]+)?$/.test(file);
  38. const { red, yellow } = require('chalk');
  39. const webpack = require('webpack');
  40. const prefix = `[vue-server-renderer-webpack-plugin]`;
  41. (exports.warn = msg => console.error(red(`${prefix} ${msg}\n`)));
  42. (exports.tip = msg => console.log(yellow(`${prefix} ${msg}\n`)));
  43. const isWebpack5 = !!(webpack.version && webpack.version[0] > 4);
  44. const onEmit = (compiler, name, stageName, hook) => {
  45. if (isWebpack5) {
  46. // Webpack >= 5.0.0
  47. compiler.hooks.compilation.tap(name, compilation => {
  48. if (compilation.compiler !== compiler) {
  49. // Ignore child compilers
  50. return;
  51. }
  52. const stage = webpack.Compilation[stageName];
  53. compilation.hooks.processAssets.tapAsync({ name, stage }, (assets, cb) => {
  54. hook(compilation, cb);
  55. });
  56. });
  57. }
  58. else if (compiler.hooks) {
  59. // Webpack >= 4.0.0
  60. compiler.hooks.emit.tapAsync(name, hook);
  61. }
  62. else {
  63. // Webpack < 4.0.0
  64. compiler.plugin('emit', hook);
  65. }
  66. };
  67. const stripModuleIdHash = id => {
  68. if (isWebpack5) {
  69. // Webpack >= 5.0.0
  70. return id.replace(/\|\w+$/, '');
  71. }
  72. // Webpack < 5.0.0
  73. return id.replace(/\s\w+$/, '');
  74. };
  75. const getAssetName = asset => {
  76. if (typeof asset === 'string') {
  77. return asset;
  78. }
  79. return asset.name;
  80. };
  81. const hash = require('hash-sum');
  82. const uniq = require('lodash.uniq');
  83. class VueSSRClientPlugin {
  84. constructor(options = {}) {
  85. //@ts-expect-error no type on options
  86. this.options = Object.assign({
  87. filename: 'vue-ssr-client-manifest.json'
  88. }, options);
  89. }
  90. apply(compiler) {
  91. const stage = 'PROCESS_ASSETS_STAGE_ADDITIONAL';
  92. onEmit(compiler, 'vue-client-plugin', stage, (compilation, cb) => {
  93. const stats = compilation.getStats().toJson();
  94. const allFiles = uniq(stats.assets.map(a => a.name));
  95. const initialFiles = uniq(Object.keys(stats.entrypoints)
  96. .map(name => stats.entrypoints[name].assets)
  97. .reduce((assets, all) => all.concat(assets), [])
  98. .map(getAssetName)
  99. .filter(file => isJS(file) || isCSS(file)));
  100. const asyncFiles = allFiles
  101. .filter(file => isJS(file) || isCSS(file))
  102. .filter(file => initialFiles.indexOf(file) < 0);
  103. const manifest = {
  104. publicPath: stats.publicPath,
  105. all: allFiles,
  106. initial: initialFiles,
  107. async: asyncFiles,
  108. modules: {
  109. /* [identifier: string]: Array<index: number> */
  110. }
  111. };
  112. const assetModules = stats.modules.filter(m => m.assets.length);
  113. const fileToIndex = asset => manifest.all.indexOf(getAssetName(asset));
  114. stats.modules.forEach(m => {
  115. // ignore modules duplicated in multiple chunks
  116. if (m.chunks.length === 1) {
  117. const cid = m.chunks[0];
  118. const chunk = stats.chunks.find(c => c.id === cid);
  119. if (!chunk || !chunk.files) {
  120. return;
  121. }
  122. const id = stripModuleIdHash(m.identifier);
  123. const files = (manifest.modules[hash(id)] =
  124. chunk.files.map(fileToIndex));
  125. // find all asset modules associated with the same chunk
  126. assetModules.forEach(m => {
  127. if (m.chunks.some(id => id === cid)) {
  128. files.push.apply(files, m.assets.map(fileToIndex));
  129. }
  130. });
  131. }
  132. });
  133. const json = JSON.stringify(manifest, null, 2);
  134. //@ts-expect-error no type on options
  135. compilation.assets[this.options.filename] = {
  136. source: () => json,
  137. size: () => json.length
  138. };
  139. cb();
  140. });
  141. }
  142. }
  143. module.exports = VueSSRClientPlugin;