-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathrollup-extensions.mjs
56 lines (46 loc) · 1.35 KB
/
rollup-extensions.mjs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
// Source: https://github.com/rollup/rollup/issues/1052
import { basename, dirname, isAbsolute, resolve } from "path";
import * as fs from "fs";
function isFile(file) {
try {
return fs.statSync(file).isFile();
} catch (err) {
return false;
}
}
function addExtensionIfNecessary(file, extensions) {
try {
const name = basename(file);
const files = fs.readdirSync(dirname(file));
if (~files.indexOf(name) && isFile(file)) return file;
for (const ext of extensions) {
if (~files.indexOf(`${name}${ext}`) && isFile(`${file}${ext}`)) {
return `${file}${ext}`;
}
}
} catch (err) {
// noop
}
return null;
}
export default function extensions({ extensions }) {
if (!extensions || !extensions.length) {
throw new Error(`Must specify { extensions: [..] } as non-empty array!`);
}
return {
name: "extensions",
resolveId(importee, importer) {
// absolute paths are left untouched
if (isAbsolute(importee)) {
return addExtensionIfNecessary(resolve(importee), extensions);
}
// if this is the entry point, resolve against cwd
if (importer === undefined) {
return addExtensionIfNecessary(resolve(process.cwd(), importee), extensions);
}
// external modules are skipped at this stage
if (importee[0] !== ".") return null;
return addExtensionIfNecessary(resolve(dirname(importer), importee), extensions);
},
};
}