gatsby-plugin-purgecss
Version:
Gatsby plugin for purgecss. Removes unused css/sass/less/stylus from files and modules. Supports Tailwindcss, Bootstrap, Bulma etc.
74 lines (73 loc) • 3.15 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.onCreateWebpackConfig = void 0;
const utils_1 = require("./utils");
const paths_1 = __importDefault(require("./paths"));
const shared_1 = require("./shared");
const debug_1 = require("./debug");
const merge_anything_1 = require("merge-anything");
const loadersRegex = /postcss-loader/;
// eslint-disable-next-line sonarjs/cognitive-complexity
const onCreateWebpackConfig = function ({ actions, stage, getConfig }, pluginOptions) {
var _a, _b, _c, _d, _e;
const { plugins, ...options } = pluginOptions;
const userOptions = options;
const defaultOptions = {
printSummary: true,
printRejected: false,
printAll: false,
debug: false,
develop: false,
tailwind: false,
ignore: [],
purgeOnly: [],
purgeCSSOptions: {
rejected: (_a = userOptions.printRejected) !== null && _a !== void 0 ? _a : false,
content: ((_b = userOptions.purgeCSSOptions) === null || _b === void 0 ? void 0 : _b.content) ? [] : [paths_1.default.src],
css: [],
safelist: { standard: ['html', 'body'] },
},
};
if (userOptions.tailwind) {
defaultOptions.purgeCSSOptions.defaultExtractor = (content) => { var _a; return (_a = content.match(/[^\s"'<>`]*[^\s"':<>`]/g)) !== null && _a !== void 0 ? _a : []; };
}
/** If safelist is an array, normalize it to object with standard key */
if (((_c = userOptions.purgeCSSOptions) === null || _c === void 0 ? void 0 : _c.safelist) &&
Array.isArray(userOptions.purgeCSSOptions.safelist)) {
userOptions.purgeCSSOptions.safelist = {
standard: [...userOptions.purgeCSSOptions.safelist],
};
}
const mergedUserOptions = (0, merge_anything_1.mergeAndConcat)(defaultOptions, userOptions);
if (mergedUserOptions.printSummary && stage === 'build-html') {
shared_1.stats.printStats();
}
if (stage === 'develop-html' || stage === 'build-html') {
return;
}
if (stage === 'develop' && !mergedUserOptions.develop) {
return;
}
const config = getConfig();
const existingRules = (_d = config.module) === null || _d === void 0 ? void 0 : _d.rules;
const purgecssloader = {
loader: paths_1.default.loader,
options: mergedUserOptions,
};
for (const rules of existingRules) {
for (const rule of (_e = rules.oneOf) !== null && _e !== void 0 ? _e : []) {
if (Array.isArray(rule.use)) {
const index = (0, utils_1.findLoader)(rule.use, loadersRegex);
(0, utils_1.insertLoader)(rule.use, index, purgecssloader);
}
}
}
actions.replaceWebpackConfig(config);
if (mergedUserOptions.debug) {
(0, debug_1.writeConfig)(getConfig());
}
};
exports.onCreateWebpackConfig = onCreateWebpackConfig;