server-plugin.js 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151
  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 { red, yellow } = require('chalk');
  38. const webpack = require('webpack');
  39. const prefix = `[vue-server-renderer-webpack-plugin]`;
  40. const warn = (exports.warn = msg => console.error(red(`${prefix} ${msg}\n`)));
  41. const tip = (exports.tip = msg => console.log(yellow(`${prefix} ${msg}\n`)));
  42. const isWebpack5 = !!(webpack.version && webpack.version[0] > 4);
  43. const validate = compiler => {
  44. if (compiler.options.target !== 'node') {
  45. warn('webpack config `target` should be "node".');
  46. }
  47. if (compiler.options.output) {
  48. if (compiler.options.output.library) {
  49. // Webpack >= 5.0.0
  50. if (compiler.options.output.library.type !== 'commonjs2') {
  51. warn('webpack config `output.library.type` should be "commonjs2".');
  52. }
  53. }
  54. else if (compiler.options.output.libraryTarget !== 'commonjs2') {
  55. // Webpack < 5.0.0
  56. warn('webpack config `output.libraryTarget` should be "commonjs2".');
  57. }
  58. }
  59. if (!compiler.options.externals) {
  60. tip('It is recommended to externalize dependencies in the server build for ' +
  61. 'better build performance.');
  62. }
  63. };
  64. const onEmit = (compiler, name, stageName, hook) => {
  65. if (isWebpack5) {
  66. // Webpack >= 5.0.0
  67. compiler.hooks.compilation.tap(name, compilation => {
  68. if (compilation.compiler !== compiler) {
  69. // Ignore child compilers
  70. return;
  71. }
  72. const stage = webpack.Compilation[stageName];
  73. compilation.hooks.processAssets.tapAsync({ name, stage }, (assets, cb) => {
  74. hook(compilation, cb);
  75. });
  76. });
  77. }
  78. else if (compiler.hooks) {
  79. // Webpack >= 4.0.0
  80. compiler.hooks.emit.tapAsync(name, hook);
  81. }
  82. else {
  83. // Webpack < 4.0.0
  84. compiler.plugin('emit', hook);
  85. }
  86. };
  87. const getAssetName = asset => {
  88. if (typeof asset === 'string') {
  89. return asset;
  90. }
  91. return asset.name;
  92. };
  93. class VueSSRServerPlugin {
  94. constructor(options = {}) {
  95. //@ts-expect-error
  96. this.options = Object.assign({
  97. filename: 'vue-ssr-server-bundle.json'
  98. }, options);
  99. }
  100. apply(compiler) {
  101. validate(compiler);
  102. const stage = 'PROCESS_ASSETS_STAGE_OPTIMIZE_TRANSFER';
  103. onEmit(compiler, 'vue-server-plugin', stage, (compilation, cb) => {
  104. const stats = compilation.getStats().toJson();
  105. const entryName = Object.keys(stats.entrypoints)[0];
  106. const entryInfo = stats.entrypoints[entryName];
  107. if (!entryInfo) {
  108. // #5553
  109. return cb();
  110. }
  111. const entryAssets = entryInfo.assets.map(getAssetName).filter(isJS);
  112. if (entryAssets.length > 1) {
  113. throw new Error(`Server-side bundle should have one single entry file. ` +
  114. `Avoid using CommonsChunkPlugin in the server config.`);
  115. }
  116. const entry = entryAssets[0];
  117. if (!entry || typeof entry !== 'string') {
  118. throw new Error(`Entry "${entryName}" not found. Did you specify the correct entry option?`);
  119. }
  120. const bundle = {
  121. entry,
  122. files: {},
  123. maps: {}
  124. };
  125. Object.keys(compilation.assets).forEach(name => {
  126. if (isJS(name)) {
  127. bundle.files[name] = compilation.assets[name].source();
  128. }
  129. else if (name.match(/\.js\.map$/)) {
  130. bundle.maps[name.replace(/\.map$/, '')] = JSON.parse(compilation.assets[name].source());
  131. }
  132. // do not emit anything else for server
  133. delete compilation.assets[name];
  134. });
  135. const json = JSON.stringify(bundle, null, 2);
  136. //@ts-expect-error
  137. const filename = this.options.filename;
  138. compilation.assets[filename] = {
  139. source: () => json,
  140. size: () => json.length
  141. };
  142. cb();
  143. });
  144. }
  145. }
  146. module.exports = VueSSRServerPlugin;