forked from babel/babel
-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
rollup-plugin-babel-source.js
84 lines (76 loc) 路 2.29 KB
/
rollup-plugin-babel-source.js
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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
const path = require("path");
const fs = require("fs");
const dirname = path.join(__dirname, "..");
module.exports = function() {
return {
name: "babel-source",
load(id) {
const matches = id.match(/packages\/(babel-[^/]+)\/src\//);
if (matches) {
// check if browser field exists for this file and replace
const packageFolder = path.join(dirname, "packages", matches[1]);
const packageJson = require(path.join(packageFolder, "package.json"));
if (
packageJson["browser"] &&
typeof packageJson["browser"] === "object"
) {
for (let nodeFile in packageJson["browser"]) {
const browserFile = packageJson["browser"][nodeFile].replace(
/^(\.\/)?lib\//,
"src/"
);
nodeFile = nodeFile.replace(/^(\.\/)?lib\//, "src/");
if (id.endsWith(nodeFile)) {
if (browserFile === false) {
return "";
}
return fs.readFileSync(
path.join(packageFolder, browserFile),
"UTF-8"
);
}
}
}
}
return null;
},
resolveId(importee) {
if (importee === "@babel/runtime/regenerator") {
return path.join(
dirname,
"packages",
"babel-runtime",
"regenerator",
"index.js"
);
}
const matches = importee.match(/^@babel\/([^/]+)$/);
if (!matches) return null;
// resolve babel package names to their src index file
const packageFolder = path.join(
dirname,
"packages",
`babel-${matches[1]}`
);
let packageJsonSource;
try {
packageJsonSource = fs.readFileSync(
path.join(packageFolder, "package.json")
);
} catch (e) {
// Some Babel packages aren't in this repository
return null;
}
const packageJson = JSON.parse(packageJsonSource);
const filename =
typeof packageJson["browser"] === "string"
? packageJson["browser"]
: packageJson["main"];
return path.join(
packageFolder,
// replace lib with src in the package.json entry
filename.replace(/^(\.\/)?lib\//, "src/")
);
},
};
};