mirror of
https://github.com/svg/svgo.git
synced 2025-07-29 20:21:14 +03:00
Support es modules (#1583)
Ref https://github.com/svg/svgo/issues/1579 In config of course. Projects with type:module can now use modules to export config ```js export default { plugins: [] } ``` Also added support for resolving svgo.config.mjs and svgo.config.cjs. Moved loadConfig tests to svgo-node tests. mjs test is skipped for now in node 10, just don't use modules there
This commit is contained in:
@ -2,6 +2,7 @@
|
||||
|
||||
const os = require('os');
|
||||
const fs = require('fs');
|
||||
const { pathToFileURL } = require('url');
|
||||
const path = require('path');
|
||||
const {
|
||||
extendDefaultPlugins,
|
||||
@ -13,7 +14,25 @@ exports.extendDefaultPlugins = extendDefaultPlugins;
|
||||
exports.createContentItem = createContentItem;
|
||||
|
||||
const importConfig = async (configFile) => {
|
||||
const config = require(configFile);
|
||||
let config;
|
||||
try {
|
||||
// dynamic import expects file url instead of path and may fail
|
||||
// when windows path is provided
|
||||
const { default: imported } = await import(pathToFileURL(configFile));
|
||||
config = imported;
|
||||
} catch (importError) {
|
||||
// TODO remove require in v3
|
||||
try {
|
||||
config = require(configFile);
|
||||
} catch (requireError) {
|
||||
// throw original error if es module is detected
|
||||
if (requireError.code === 'ERR_REQUIRE_ESM') {
|
||||
throw importError;
|
||||
} else {
|
||||
throw requireError;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (config == null || typeof config !== 'object' || Array.isArray(config)) {
|
||||
throw Error(`Invalid config file "${configFile}"`);
|
||||
}
|
||||
@ -40,9 +59,17 @@ const loadConfig = async (configFile, cwd = process.cwd()) => {
|
||||
let dir = cwd;
|
||||
// eslint-disable-next-line no-constant-condition
|
||||
while (true) {
|
||||
const file = path.join(dir, 'svgo.config.js');
|
||||
if (await isFile(file)) {
|
||||
return await importConfig(file);
|
||||
const js = path.join(dir, 'svgo.config.js');
|
||||
if (await isFile(js)) {
|
||||
return await importConfig(js);
|
||||
}
|
||||
const mjs = path.join(dir, 'svgo.config.mjs');
|
||||
if (await isFile(mjs)) {
|
||||
return await importConfig(mjs);
|
||||
}
|
||||
const cjs = path.join(dir, 'svgo.config.cjs');
|
||||
if (await isFile(cjs)) {
|
||||
return await importConfig(cjs);
|
||||
}
|
||||
const parent = path.dirname(dir);
|
||||
if (dir === parent) {
|
||||
|
Reference in New Issue
Block a user