Skip to content

fix: support ESM version of postcss.config.js #614

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Nov 29, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
80 changes: 78 additions & 2 deletions src/utils.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import path from "path";
import url from "url";
import Module from "module";

import { klona } from "klona/full";
import { cosmiconfig } from "cosmiconfig";
import { cosmiconfig, defaultLoaders } from "cosmiconfig";

import SyntaxError from "./Error";

Expand Down Expand Up @@ -47,7 +48,82 @@ async function loadConfig(loaderContext, config, postcssOptions) {
throw new Error(`No PostCSS config found in: ${searchPath}`);
}

const explorer = cosmiconfig("postcss");
const moduleName = "postcss";
const explorer = cosmiconfig(moduleName, {
searchPlaces: [
"package.json",
`.${moduleName}rc`,
`.${moduleName}rc.json`,
`.${moduleName}rc.yaml`,
`.${moduleName}rc.yml`,
`.${moduleName}rc.js`,
`.${moduleName}rc.mjs`,
`.${moduleName}rc.cjs`,
`.config/${moduleName}rc`,
`.config/${moduleName}rc.json`,
`.config/${moduleName}rc.yaml`,
`.config/${moduleName}rc.yml`,
`.config/${moduleName}rc.js`,
`.config/${moduleName}rc.mjs`,
`.config/${moduleName}rc.cjs`,
`${moduleName}.config.js`,
`${moduleName}.config.mjs`,
`${moduleName}.config.cjs`,
],
loaders: {
".js": async (...args) => {
let result;

try {
result = defaultLoaders[".js"](...args);
} catch (error) {
let importESM;

try {
// eslint-disable-next-line no-new-func
importESM = new Function("id", "return import(id);");
} catch (e) {
importESM = null;
}

if (
error.code === "ERR_REQUIRE_ESM" &&
url.pathToFileURL &&
importESM
) {
const urlForConfig = url.pathToFileURL(args[0]);

result = await importESM(urlForConfig);
} else {
throw error;
}
}

return result;
},
".mjs": async (...args) => {
let result;
let importESM;

try {
// eslint-disable-next-line no-new-func
importESM = new Function("id", "return import(id);");
} catch (e) {
importESM = null;
}

if (url.pathToFileURL && importESM) {
const urlForConfig = url.pathToFileURL(args[0]);

result = await importESM(urlForConfig);
} else {
throw new Error("ESM is not supported");
}

return result;
},
},
});

let result;

Expand Down