1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 |
|
7 |
|
8 |
|
9 |
|
10 |
|
11 |
|
12 | const { dirname } = require('path');
|
13 |
|
14 | const isObject = require('is-plain-obj');
|
15 | const pkgConf = require('pkg-conf');
|
16 | const { WebpackPluginServe } = require('webpack-plugin-serve');
|
17 |
|
18 | const { prepare } = require('./flags');
|
19 |
|
20 | const applyEntry = (entry) => {
|
21 | const pluginEntry = 'webpack-plugin-serve/client';
|
22 |
|
23 | if (Array.isArray(entry)) {
|
24 | entry.push(pluginEntry);
|
25 | } else if (isObject(entry)) {
|
26 | const keys = Object.keys(entry);
|
27 | for (const key of keys) {
|
28 | entry[key] = applyEntry(entry[key]);
|
29 | }
|
30 | } else {
|
31 | entry = [entry, pluginEntry];
|
32 | }
|
33 |
|
34 | return entry;
|
35 | };
|
36 |
|
37 | const applyPlugin = (config, flags, plugin, attach = false) => {
|
38 | const isEmpty = Object.keys(config).length === 0;
|
39 |
|
40 | if (!config.plugins) {
|
41 | config.plugins = [];
|
42 | }
|
43 |
|
44 | config.plugins.push(attach ? plugin.attach() : plugin);
|
45 |
|
46 | if (isEmpty) {
|
47 | config.entry = ['./src'];
|
48 | }
|
49 |
|
50 |
|
51 |
|
52 | if (!attach && flags.watch !== false) {
|
53 | config.watch = true;
|
54 | }
|
55 |
|
56 | config.entry = applyEntry(config.entry);
|
57 |
|
58 | return config;
|
59 | };
|
60 |
|
61 | const apply = async (config, flags, configPath) => {
|
62 | const flagOptions = prepare(flags);
|
63 | const pkgConfig = await pkgConf('serve', { cwd: dirname(configPath) });
|
64 | const options = Object.assign({}, pkgConfig, flagOptions);
|
65 | const plugin = new WebpackPluginServe(options);
|
66 |
|
67 | if (flags.all) {
|
68 | if (Array.isArray(config)) {
|
69 | config = config.map((c, index) => applyPlugin(c, flags, plugin, index > 0));
|
70 | } else {
|
71 | config = applyPlugin(config, flags, plugin);
|
72 | }
|
73 | } else {
|
74 | [config] = [].concat(config);
|
75 | config = applyPlugin(config, flags, plugin);
|
76 | }
|
77 |
|
78 | return config;
|
79 | };
|
80 |
|
81 | module.exports = { apply };
|