UNPKG

2.75 kBJavaScriptView Raw
1'use strict';
2
3/* */
4
5var isJS = function (file) { return /\.js(\?[^.]+)?$/.test(file); };
6
7var ref = require('chalk');
8var red = ref.red;
9var yellow = ref.yellow;
10
11var prefix = "[vue-server-renderer-webpack-plugin]";
12var warn = exports.warn = function (msg) { return console.error(red((prefix + " " + msg + "\n"))); };
13var tip = exports.tip = function (msg) { return console.log(yellow((prefix + " " + msg + "\n"))); };
14
15var validate = function (compiler) {
16 if (compiler.options.target !== 'node') {
17 warn('webpack config `target` should be "node".');
18 }
19
20 if (compiler.options.output && compiler.options.output.libraryTarget !== 'commonjs2') {
21 warn('webpack config `output.libraryTarget` should be "commonjs2".');
22 }
23
24 if (!compiler.options.externals) {
25 tip(
26 'It is recommended to externalize dependencies in the server build for ' +
27 'better build performance.'
28 );
29 }
30};
31
32var VueSSRServerPlugin = function VueSSRServerPlugin (options) {
33 if ( options === void 0 ) options = {};
34
35 this.options = Object.assign({
36 filename: 'vue-ssr-server-bundle.json'
37 }, options);
38};
39
40VueSSRServerPlugin.prototype.apply = function apply (compiler) {
41 var this$1 = this;
42
43 validate(compiler);
44
45 compiler.plugin('emit', function (compilation, cb) {
46 var stats = compilation.getStats().toJson();
47 var entryName = Object.keys(stats.entrypoints)[0];
48 var entryInfo = stats.entrypoints[entryName];
49
50 if (!entryInfo) {
51 // #5553
52 return cb()
53 }
54
55 var entryAssets = entryInfo.assets.filter(isJS);
56
57 if (entryAssets.length > 1) {
58 throw new Error(
59 "Server-side bundle should have one single entry file. " +
60 "Avoid using CommonsChunkPlugin in the server config."
61 )
62 }
63
64 var entry = entryAssets[0];
65 if (!entry || typeof entry !== 'string') {
66 throw new Error(
67 ("Entry \"" + entryName + "\" not found. Did you specify the correct entry option?")
68 )
69 }
70
71 var bundle = {
72 entry: entry,
73 files: {},
74 maps: {}
75 };
76
77 stats.assets.forEach(function (asset) {
78 if (asset.name.match(/\.js$/)) {
79 bundle.files[asset.name] = compilation.assets[asset.name].source();
80 } else if (asset.name.match(/\.js\.map$/)) {
81 bundle.maps[asset.name.replace(/\.map$/, '')] = JSON.parse(compilation.assets[asset.name].source());
82 }
83 // do not emit anything else for server
84 delete compilation.assets[asset.name];
85 });
86
87 var json = JSON.stringify(bundle, null, 2);
88 var filename = this$1.options.filename;
89
90 compilation.assets[filename] = {
91 source: function () { return json; },
92 size: function () { return json.length; }
93 };
94
95 cb();
96 });
97};
98
99module.exports = VueSSRServerPlugin;