UNPKG

2.17 kBJavaScriptView Raw
1/*
2 Copyright © 2018 Andrew Powell
3
4 This Source Code Form is subject to the terms of the Mozilla Public
5 License, v. 2.0. If a copy of the MPL was not distributed with this
6 file, You can obtain one at http://mozilla.org/MPL/2.0/.
7
8 The above copyright notice and this permission notice shall be
9 included in all copies or substantial portions of this Source Code Form.
10*/
11/* eslint-disable no-param-reassign */
12const { dirname } = require('path');
13
14const isObject = require('is-plain-obj');
15const pkgConf = require('pkg-conf');
16const { WebpackPluginServe } = require('webpack-plugin-serve');
17
18const { prepare } = require('./flags');
19
20const 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
37const 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 // apply watch only if hmr or liveReload is on, if it's the first config, and if --no-watch is not
51 // specified
52 if (!attach && flags.watch !== false) {
53 config.watch = true;
54 }
55
56 config.entry = applyEntry(config.entry);
57
58 return config;
59};
60
61const 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
81module.exports = { apply };