UNPKG

2.96 kBJavaScriptView Raw
1"use strict";
2var __importDefault = (this && this.__importDefault) || function (mod) {
3 return (mod && mod.__esModule) ? mod : { "default": mod };
4};
5Object.defineProperty(exports, "__esModule", { value: true });
6const purgecss_1 = __importDefault(require("purgecss"));
7const shared_1 = require("./shared");
8const debug_1 = require("./debug");
9const utils_1 = require("./utils");
10// eslint-disable-next-line sonarjs/cognitive-complexity
11const purgeCSSLoader = function loader(source) {
12 if (Buffer.isBuffer(source)) {
13 console.warn('gatsby-plugin-purgecss: Cannot process raw buffers');
14 return;
15 }
16 const callback = this.async();
17 const options = this.getOptions();
18 if (options.printSummary) {
19 shared_1.stats.addSize(source);
20 }
21 if (Array.isArray(options.ignore) && options.ignore.length > 0) {
22 const normalizedPath = (0, utils_1.normalizePath)(this.resourcePath, this.rootContext);
23 if (options.ignore.some((file) => normalizedPath.includes(file))) {
24 console.log('gatsby-plugin-purgecss: Ignored', this.resourcePath);
25 shared_1.stats.addRemovedSize(source);
26 callback(undefined, source);
27 return;
28 }
29 }
30 if (Array.isArray(options.purgeOnly) && options.purgeOnly.length > 0) {
31 const normalizedPath = (0, utils_1.normalizePath)(this.resourcePath, this.rootContext);
32 if (options.purgeOnly.some((file) => normalizedPath.includes(file))) {
33 console.log('gatsby-plugin-purgecss: Only processing', this.resourcePath);
34 }
35 else {
36 shared_1.stats.addRemovedSize(source);
37 callback(undefined, source);
38 return;
39 }
40 }
41 void new purgecss_1.default()
42 .purge({
43 ...options.purgeCSSOptions,
44 css: [{ raw: source }],
45 })
46 .then((result) => {
47 if (options.printSummary) {
48 shared_1.stats.addRemovedSize(result[0].css);
49 }
50 const rejected = result[0].rejected;
51 if (options.printRejected && Array.isArray(rejected)) {
52 const filtered = rejected.map((value) => {
53 return value.replace('\n', '');
54 });
55 console.log(utils_1.color.FgGreen, '\nFrom:', this.resourcePath);
56 console.log(utils_1.color.Reset, 'Removed Selectors:', options.printAll ? JSON.stringify(filtered) : filtered);
57 }
58 callback(undefined, result[0].css);
59 })
60 .catch((error) => {
61 console.log('\ngatsby-plugin-purgecss: Could not parse file, skipping. Your build will not break.\n', this.resourcePath, error);
62 if (options.debug) {
63 (0, debug_1.writeAppendError)(error);
64 }
65 else {
66 console.log('Use debug option to investigate further.');
67 }
68 callback(error, source);
69 });
70};
71exports.default = purgeCSSLoader;