1
0
mirror of https://github.com/svg/svgo.git synced 2025-07-29 20:21:14 +03:00

Implement loadConfig utility (#1328)

Ref https://github.com/svg/svgo/issues/1327

Config file now can only be js. `svgo.config.js` is searched by default.
Otherwise any js module specified in `--config` cli flag.

Config loader is exposed in entry point as `loadConfig(configFile, cwd)`.
This commit is contained in:
Bogdan Chadkin
2021-02-16 19:11:13 +03:00
committed by GitHub
parent d273b26605
commit a6f14018ee
12 changed files with 142 additions and 29 deletions

54
lib/svgo-node.js Normal file
View File

@ -0,0 +1,54 @@
'use strict';
const fs = require('fs');
const path = require('path');
const {
extendDefaultPlugins,
optimize,
createContentItem,
} = require('./svgo.js');
const importConfig = async configFile => {
try {
const config = require(configFile);
if (config == null || typeof config !== 'object' || Array.isArray(config)) {
throw Error(`Invalid config file "${configFile}"`);
}
return config;
} catch (error) {
if (error.code === 'MODULE_NOT_FOUND') {
return null;
}
throw error;
}
};
const loadConfig = async (configFile, cwd = process.cwd()) => {
if (configFile != null) {
if (path.isAbsolute(configFile)) {
return await importConfig(configFile);
} else {
return await importConfig(path.join(cwd, configFile));
}
}
let dir = cwd;
while (true) {
try {
const file = path.join(dir, "svgo.config.js");
const stats = await fs.promises.stat(file);
if (stats.isFile()) {
return await importConfig(file);
}
} catch {}
const parent = path.dirname(dir);
if (dir === parent) {
return null;
}
dir = parent;
}
};
exports.loadConfig = loadConfig;
exports.extendDefaultPlugins = extendDefaultPlugins;
exports.optimize = optimize;
exports.createContentItem = createContentItem;