Skip to content

Commit 955085f

Browse files
fix: support ESM version of postcss.config.js and postcss.config.mjs (#614)
1 parent b0f4749 commit 955085f

File tree

1 file changed

+78
-2
lines changed

1 file changed

+78
-2
lines changed

src/utils.js

+78-2
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,9 @@
11
import path from "path";
2+
import url from "url";
23
import Module from "module";
34

45
import { klona } from "klona/full";
5-
import { cosmiconfig } from "cosmiconfig";
6+
import { cosmiconfig, defaultLoaders } from "cosmiconfig";
67

78
import SyntaxError from "./Error";
89

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

50-
const explorer = cosmiconfig("postcss");
51+
const moduleName = "postcss";
52+
const explorer = cosmiconfig(moduleName, {
53+
searchPlaces: [
54+
"package.json",
55+
`.${moduleName}rc`,
56+
`.${moduleName}rc.json`,
57+
`.${moduleName}rc.yaml`,
58+
`.${moduleName}rc.yml`,
59+
`.${moduleName}rc.js`,
60+
`.${moduleName}rc.mjs`,
61+
`.${moduleName}rc.cjs`,
62+
`.config/${moduleName}rc`,
63+
`.config/${moduleName}rc.json`,
64+
`.config/${moduleName}rc.yaml`,
65+
`.config/${moduleName}rc.yml`,
66+
`.config/${moduleName}rc.js`,
67+
`.config/${moduleName}rc.mjs`,
68+
`.config/${moduleName}rc.cjs`,
69+
`${moduleName}.config.js`,
70+
`${moduleName}.config.mjs`,
71+
`${moduleName}.config.cjs`,
72+
],
73+
loaders: {
74+
".js": async (...args) => {
75+
let result;
76+
77+
try {
78+
result = defaultLoaders[".js"](...args);
79+
} catch (error) {
80+
let importESM;
81+
82+
try {
83+
// eslint-disable-next-line no-new-func
84+
importESM = new Function("id", "return import(id);");
85+
} catch (e) {
86+
importESM = null;
87+
}
88+
89+
if (
90+
error.code === "ERR_REQUIRE_ESM" &&
91+
url.pathToFileURL &&
92+
importESM
93+
) {
94+
const urlForConfig = url.pathToFileURL(args[0]);
95+
96+
result = await importESM(urlForConfig);
97+
} else {
98+
throw error;
99+
}
100+
}
101+
102+
return result;
103+
},
104+
".mjs": async (...args) => {
105+
let result;
106+
let importESM;
107+
108+
try {
109+
// eslint-disable-next-line no-new-func
110+
importESM = new Function("id", "return import(id);");
111+
} catch (e) {
112+
importESM = null;
113+
}
114+
115+
if (url.pathToFileURL && importESM) {
116+
const urlForConfig = url.pathToFileURL(args[0]);
117+
118+
result = await importESM(urlForConfig);
119+
} else {
120+
throw new Error("ESM is not supported");
121+
}
122+
123+
return result;
124+
},
125+
},
126+
});
51127

52128
let result;
53129

0 commit comments

Comments
 (0)