forked from preconstruct/preconstruct
-
Notifications
You must be signed in to change notification settings - Fork 0
/
rollup.ts
214 lines (204 loc) Β· 6.28 KB
/
rollup.ts
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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
import resolve from "@rollup/plugin-node-resolve";
// @ts-ignore
import alias from "@rollup/plugin-alias";
import cjs from "@rollup/plugin-commonjs";
import replace from "@rollup/plugin-replace";
import chalk from "chalk";
import path from "path";
import builtInModules from "builtin-modules";
import { Package } from "../package";
import { Entrypoint } from "../entrypoint";
import { RollupOptions, Plugin } from "rollup";
import { Aliases } from "./aliases";
import { FatalError, BatchError } from "../errors";
import rewriteBabelRuntimeHelpers from "../rollup-plugins/rewrite-babel-runtime-helpers";
import flowAndNodeDevProdEntry from "../rollup-plugins/flow-and-prod-dev-entry";
import typescriptDeclarations from "../rollup-plugins/typescript-declarations";
import json from "@rollup/plugin-json";
import babel from "../rollup-plugins/babel";
import terser from "../rollup-plugins/terser";
import { getNameForDistForEntrypoint } from "../utils";
import { EXTENSIONS } from "../constants";
import { inlineProcessEnvNodeEnv } from "../rollup-plugins/inline-process-env-node-env";
import normalizePath from "normalize-path";
// this makes sure nested imports of external packages are external
const makeExternalPredicate = (externalArr: string[]) => {
if (externalArr.length === 0) {
return () => false;
}
const pattern = new RegExp(`^(${externalArr.join("|")})($|/)`);
return (id: string) => pattern.test(id);
};
export type RollupConfigType =
| "umd"
| "browser"
| "node-dev"
| "node-prod"
| "worker";
export let getRollupConfig = (
pkg: Package,
entrypoints: Array<Entrypoint>,
aliases: Aliases,
type: RollupConfigType,
reportTransformedFile: (filename: string) => void
): RollupOptions => {
let external = [];
if (pkg.json.peerDependencies) {
external.push(...Object.keys(pkg.json.peerDependencies));
}
if (pkg.json.dependencies && type !== "umd") {
external.push(...Object.keys(pkg.json.dependencies));
}
if (type === "node-dev" || type === "node-prod") {
external.push(...builtInModules);
}
let input: Record<string, string> = {};
entrypoints.forEach((entrypoint) => {
input[
path.relative(
pkg.directory,
path.join(
entrypoint.directory,
"dist",
getNameForDistForEntrypoint(entrypoint)
)
)
] = entrypoint.source;
});
let warnings: Array<FatalError> = [];
const config: RollupOptions = {
input,
external: makeExternalPredicate(external),
onwarn: (warning) => {
if (typeof warning === "string") {
warnings.push(
new FatalError(
`An unhandled Rollup error occurred: ${chalk.red(
// @ts-ignore
warning.toString()
)}`,
pkg.name
)
);
return;
}
switch (warning.code) {
case "CIRCULAR_DEPENDENCY":
case "EMPTY_BUNDLE":
case "EVAL":
case "UNUSED_EXTERNAL_IMPORT": {
break;
}
case "UNRESOLVED_IMPORT": {
if (!warning.source!.startsWith(".")) {
warnings.push(
new FatalError(
`"${warning.source}" is imported by "${normalizePath(
path.relative(pkg.directory, warning.importer!)
)}" but the package is not specified in dependencies or peerDependencies`,
pkg.name
)
);
return;
}
}
case "THIS_IS_UNDEFINED": {
if (type === "umd") {
return;
}
warnings.push(
new FatalError(
`"${normalizePath(
path.relative(pkg.directory, warning.loc!.file!)
)}" used \`this\` keyword at the top level of an ES module. You can read more about this at ${warning.url!} and fix this issue that has happened here:\n\n${warning.frame!}\n`,
pkg.name
)
);
return;
}
default: {
warnings.push(
new FatalError(
`An unhandled Rollup error occurred: ${chalk.red(
warning.toString()
)}`,
pkg.name
)
);
}
}
},
plugins: [
{
name: "throw-warnings",
buildEnd() {
if (warnings.length) {
throw new BatchError(warnings);
}
},
} as Plugin,
type === "node-prod" && flowAndNodeDevProdEntry(pkg, warnings),
type === "node-prod" && typescriptDeclarations(pkg),
babel({
cwd: pkg.project.directory,
reportTransformedFile,
babelRuntime: (() => {
for (const dep of [
"@babel/runtime",
"@babel/runtime-corejs2",
"@babel/runtime-corejs3",
]) {
const range = pkg.json.dependencies?.[dep];
if (range !== undefined) {
return { range, name: dep };
}
}
})(),
}),
type === "umd" &&
cjs({
include: ["**/node_modules/**", "node_modules/**"],
}),
rewriteBabelRuntimeHelpers(),
json({
namedExports: false,
}),
type === "umd" &&
alias({
entries: aliases,
}),
resolve({
extensions: EXTENSIONS,
browser: type === "umd",
customResolveOptions: {
moduleDirectory: type === "umd" ? "node_modules" : [],
},
}),
type === "umd" && inlineProcessEnvNodeEnv({ sourceMap: true }),
type === "umd" &&
terser({
sourceMap: true,
compress: true,
}),
type === "node-prod" && inlineProcessEnvNodeEnv({ sourceMap: false }),
(type === "browser" || type === "umd") &&
replace({
values: {
["typeof " + "document"]: JSON.stringify("object"),
["typeof " + "window"]: JSON.stringify("object"),
},
preventAssignment: true,
}),
type === "worker" &&
replace({
values: {
["typeof " + "document"]: JSON.stringify("undefined"),
["typeof " + "window"]: JSON.stringify("undefined"),
["typeof " + "process"]: JSON.stringify("undefined"),
},
preventAssignment: true,
}),
].filter((x): x is Plugin => !!x),
};
return config;
};