UNPKG

2.87 kBJavaScriptView Raw
1"use strict";
2
3Object.defineProperty(exports, "__esModule", {
4 value: true
5});
6exports.default = void 0;
7
8var _full = require("klona/full");
9
10class InvalidConfigError extends Error {}
11
12function log(error, metaData, type) {
13 if (metaData.result) {
14 if (type === 'error') {
15 metaData.result.errors.push(error);
16 } else {
17 metaData.result.warnings.push(error);
18 }
19
20 return;
21 }
22
23 throw error;
24}
25
26function normalizeConfig(minimizerOptions, metaData = {}) {
27 if (!minimizerOptions || !minimizerOptions.plugins || minimizerOptions.plugins && minimizerOptions.plugins.length === 0) {
28 log(new Error('No plugins found for `imagemin`. Please read documentation.'), metaData);
29 return minimizerOptions;
30 }
31
32 const imageminConfig = (0, _full.klona)(minimizerOptions);
33
34 if (!imageminConfig.pluginsMeta) {
35 imageminConfig.pluginsMeta = [];
36 }
37
38 imageminConfig.plugins = imageminConfig.plugins.map(plugin => {
39 const isPluginArray = Array.isArray(plugin);
40
41 if (typeof plugin === 'string' || isPluginArray) {
42 const pluginName = isPluginArray ? plugin[0] : plugin; // eslint-disable-next-line no-undefined
43
44 const pluginOptions = isPluginArray ? plugin[1] : undefined;
45 let requiredPlugin = null;
46 let requiredPluginName = `imagemin-${pluginName}`;
47
48 try {
49 // eslint-disable-next-line import/no-dynamic-require, global-require
50 requiredPlugin = require(requiredPluginName)(pluginOptions);
51 } catch (ignoreError) {
52 requiredPluginName = pluginName;
53
54 try {
55 // eslint-disable-next-line import/no-dynamic-require, global-require
56 requiredPlugin = require(requiredPluginName)(pluginOptions);
57 } catch (ignoreError1) {
58 const pluginNameForError = pluginName.startsWith('imagemin') ? pluginName : `imagemin-${pluginName}`;
59 log(new Error(`Unknown plugin: ${pluginNameForError}\n\nDid you forget to install the plugin?\nYou can install it with:\n\n$ npm install ${pluginNameForError} --save-dev\n$ yarn add ${pluginNameForError} --dev`), metaData);
60 return false;
61 } // Nothing
62
63 }
64
65 let version = 'unknown';
66
67 try {
68 // eslint-disable-next-line import/no-dynamic-require, global-require
69 ({
70 version
71 } = require(`${requiredPluginName}/package.json`));
72 } catch (ignoreVersion) {// Nothing
73 }
74
75 imageminConfig.pluginsMeta.push([{
76 name: requiredPluginName,
77 options: pluginOptions || {},
78 version
79 }]);
80 return requiredPlugin;
81 }
82
83 log(new InvalidConfigError(`Invalid plugin configuration "${JSON.stringify(plugin)}, plugin configuraion should be 'string' or '[string, object]'"`), metaData, 'error');
84 return false;
85 }).filter(Boolean);
86 return imageminConfig;
87}
88
89var _default = normalizeConfig;
90exports.default = _default;
\No newline at end of file