UNPKG

4.27 kBJavaScriptView Raw
1"use strict";
2
3Object.defineProperty(exports, "__esModule", {
4 value: true
5});
6exports.default = void 0;
7
8var _path = require("path");
9
10var _filesize = _interopRequireDefault(require("filesize"));
11
12var _imagemin = require("imagemin");
13
14var _plugin = require("@parcel/plugin");
15
16var _utils = require("@parcel/utils");
17
18var _package = require("../package.json");
19
20function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
21
22function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; }
23
24function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
25
26// Constants.
27const DEFAULT_PLUGINS = {
28 'imagemin-gifsicle': {
29 optimizationLevel: 3
30 },
31 'imagemin-mozjpeg': {
32 quality: 80
33 },
34 'imagemin-pngquant': {
35 speed: 1,
36 strip: true
37 },
38 'imagemin-svgo': {},
39 'imagemin-webp': {}
40};
41const BUNDLE_TYPE_WEBP = 'webp'; // Helpers.
42
43const omit = (obj, prop) => {
44 const {
45 [prop]: _,
46 ...result
47 } = obj;
48 return result;
49}; // Plugin configuration importer.
50
51
52let projectPackagePromise = null;
53
54const getPluginConfig = projectRoot => {
55 // Import only once.
56 if (projectPackagePromise == null) {
57 projectPackagePromise = Promise.resolve(`${(0, _path.join)(projectRoot, 'package.json')}`).then(s => _interopRequireWildcard(require(s))).then(pkgConfig => {
58 const plugins = Object.entries({ // Merge default and package configurations.
59 ...DEFAULT_PLUGINS,
60 ...pkgConfig[_package.name]
61 }).filter(([, options]) => options) // Filter out disabled plugins.
62 // eslint-disable-next-line global-require, import/no-dynamic-require
63 .map(([plugin, options]) => [plugin, require(plugin)(options)]);
64 return Object.fromEntries(plugins);
65 });
66 }
67
68 return projectPackagePromise;
69}; // Exports.
70
71
72var _default = new _plugin.Optimizer({
73 async optimize({
74 bundle,
75 contents,
76 logger,
77 map,
78 options
79 }) {
80 const {
81 env,
82 type: bundleType
83 } = bundle; // Skip optimizer if we don't want to minify.
84
85 if (!env.minify) {
86 return {
87 contents,
88 map
89 };
90 }
91
92 const {
93 projectRoot
94 } = options;
95 const config = await getPluginConfig(projectRoot); // The WebP plugin is greedy and will attempt to convert any file to WebP.
96 // We only want to optimize, not convert, so remove WebP plugin unless
97 // bundle type is explicitly set to WebP.
98
99 const plugins = bundleType === BUNDLE_TYPE_WEBP ? config : omit(config, 'imagemin-webp'); // Optimize.
100
101 const buffer = await (0, _utils.blobToBuffer)(contents);
102 const output = await (0, _imagemin.buffer)(buffer, {
103 plugins: Object.values(plugins)
104 }); // Return original when optimization is larger.
105
106 const inputLength = buffer.length;
107 const outputLength = output.length;
108
109 if (inputLength <= outputLength) {
110 return {
111 contents: buffer,
112 map
113 };
114 } // Log optimization.
115
116
117 const {
118 filePath: bundlePath
119 } = bundle.getMainEntry();
120 const filePath = (0, _path.relative)(projectRoot, bundlePath);
121 const savings = parseInt((1 - outputLength / inputLength) * 100, 10);
122 logger.info({
123 message: `${filePath}: ${(0, _filesize.default)(inputLength)}${(0, _filesize.default)(outputLength)} (-${savings}%)`,
124 filePath: bundlePath,
125 language: bundleType
126 }); // Return the optimization.
127
128 return {
129 contents: output
130 };
131 }
132
133});
134
135exports.default = _default;
\No newline at end of file