Skip to content

Commit 2c40a50

Browse files
committed
Config file
1 parent 5c68787 commit 2c40a50

File tree

2 files changed

+22
-1
lines changed

2 files changed

+22
-1
lines changed

src/constants/constants.js

+2
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
export const IGNORE_ANNOTATION = "purifycss ignore"
2+
export const CONFIG_FILENAME = "purgecss.config.js"
23

34
// Error Message
5+
export const ERROR_CONFIG_FILE_LOADING = "Error loading the config file"
46
export const ERROR_MISSING_CONTENT = "No content provided."
57
export const ERROR_MISSING_CSS = "No css provided."
68
export const ERROR_EXTRACTER_FAILED =

src/index.js

+20-1
Original file line numberDiff line numberDiff line change
@@ -2,11 +2,14 @@
22
import type { ExtractersObj, Options } from "./../flow/index.js"
33

44
import fs from "fs"
5+
import path from "path"
56
import glob from "glob"
67
import defaultOptions from "./constants/defaultOptions"
78
import postcss from "postcss"
89
import selectorParser from "postcss-selector-parser"
910
import {
11+
CONFIG_FILENAME,
12+
ERROR_CONFIG_FILE_LOADING,
1013
ERROR_MISSING_CONTENT,
1114
ERROR_MISSING_CSS,
1215
ERROR_EXTRACTER_FAILED,
@@ -28,12 +31,28 @@ class Purgecss {
2831
options: Options
2932
selectors: Set<string>
3033

31-
constructor(options: Options) {
34+
constructor(options: Options | string) {
35+
if (typeof options === "string" || typeof options === "undefined")
36+
options = this.loadConfigFile(options)
3237
this.checkOptions(options)
3338
this.options = Object.assign(defaultOptions, options)
3439
this.selectors = new Set()
3540
}
3641

42+
loadConfigFile(configFile?: string) {
43+
const pathConfig = typeof configFile === "undefined"
44+
? CONFIG_FILENAME
45+
: configFile
46+
let options
47+
try {
48+
const t = path.resolve(process.cwd(), pathConfig)
49+
options = require(t)
50+
} catch (e) {
51+
throw new Error(ERROR_CONFIG_FILE_LOADING + e.message)
52+
}
53+
return options
54+
}
55+
3756
checkOptions(options: Options) {
3857
if (typeof options !== "object") throw new TypeError(ERROR_OPTIONS_TYPE)
3958
if (!options.content || !options.content.length)

0 commit comments

Comments
 (0)