-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbundle.js
211 lines (186 loc) · 5.65 KB
/
bundle.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
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
import { join } from "node:path";
import { fileURLToPath } from "node:url";
import console from "console-ansi";
import { rollup, watch } from "rollup";
import nodeResolve from "@rollup/plugin-node-resolve";
import commonjs from "@rollup/plugin-commonjs";
import polyfillNode from "rollup-plugin-polyfill-node";
import json from "@rollup/plugin-json";
import replace from "@rollup/plugin-replace";
import commonjsNamedExports from "rollup-plugin-commonjs-named-exports";
import noOp from "rollup-plugin-no-op";
import deepmerge from "deepmerge";
import { FILES_GLOB, secondsFormatter } from "./utils.js";
const __dirname = fileURLToPath(new URL(".", import.meta.url));
let transpiler;
let minifier;
const parsePluginOptions = (plugins, options) =>
Object.entries(plugins)
.filter(([name]) => {
if (!options[name]) return true;
return options[name].enabled ?? true;
})
.map(([name, pluginFactory]) => pluginFactory(options[name]));
const groupExtraPlugins = (plugins) =>
plugins.reduce(
(groupedPlugins, plugin) => {
if (plugin.enforce === "pre") groupedPlugins["pre"].push(plugin);
else if (plugin.enforce === "post") groupedPlugins["post"].push(plugin);
else groupedPlugins["normal"].push(plugin);
delete plugin.enforce;
return groupedPlugins;
},
{ pre: [], normal: [], post: [] },
);
const formatRollupLog = (
{ name, cause, loc, message, frame },
level = "error",
) => {
name = name || cause?.name;
name = name ? ` ${name}` : "";
console[level](
`rollup${name}: ${message}`,
loc ? `at ${loc.file}(${loc.line},${loc.column}): ` : "",
);
if (frame) globalThis.console[level](frame);
};
const bundle = async (options = {}) => {
const label = `bundle`;
console.time(label);
const sourceMap = options.rollup.sourceMap;
let plugins = options.rollup.input?.plugins;
if (!plugins) {
let minify = options.minify;
minify ??= options.NODE_ENV === "production";
const pluginsOptions = deepmerge(
{
nodeResolve: { modulePaths: [join(__dirname, "node_modules")] },
commonjs: { sourceMap, strictRequires: "auto" },
polyfillNode: {
include: [...FILES_GLOB.javascript, ...FILES_GLOB.commonjs],
},
replace: {
[["process", "env", "NODE_ENV"].join(".")]: JSON.stringify(
options.NODE_ENV,
),
preventAssignment: true,
},
json: { compact: minify },
noOp: { ids: ["inspector"] },
},
options.rollup.pluginsOptions,
);
if (options.transpiler === "esbuild") {
transpiler = await (
await import("rollup-plugin-esbuild")
).default({ minify, sourceMap, ...options.esbuild });
} else if (options.transpiler === "swc") {
transpiler = await (
await import("@rollup/plugin-swc")
).default({
swc: {
cwd: options.cwd,
minify,
sourceMaps: sourceMap,
...options.swc,
},
});
} else {
transpiler = await (
await import("@rollup/plugin-babel")
).babel({ cwd: options.cwd, babelHelpers: "runtime", ...options.babel });
if (minify) {
minifier = await (await import("@rollup/plugin-terser")).default();
}
}
const { pre, normal, post } = groupExtraPlugins(
options.rollup.extraPlugins.filter(Boolean),
);
plugins = [
...pre,
...parsePluginOptions(
{
nodeResolve,
commonjs,
commonjsNamedExports,
polyfillNode,
replace,
json,
noOp,
},
pluginsOptions,
),
...normal,
transpiler,
...post,
minifier,
].filter(Boolean);
}
let bundle;
let result;
try {
/** @type {import("rollup").InputOptions} */
const inputOptions = {
// input,
onLog(level, log) {
if (
["THIS_IS_UNDEFINED", "EVAL", "MODULE_LEVEL_DIRECTIVE"].includes(
log.code,
) ||
(log.code === "CIRCULAR_DEPENDENCY" &&
["node_modules", "polyfill-node", "@babel"].some((filter) =>
log.message.includes(filter),
))
) {
return;
}
formatRollupLog(log, level);
},
...options.rollup.input,
plugins,
};
/** @type {import("rollup").OutputOptions} */
const outputOptions = {
// dir,
sourcemap: sourceMap,
chunkFileNames: "_chunks/[name]-[hash].js",
manualChunks(id) {
if (id.includes("core-js/") || id.includes("polyfill-node")) {
return "polyfills";
}
},
...options.rollup.output,
};
if (options.rollup.watch) {
console.info(`bundle: watching...`);
const watcher = watch({
...inputOptions,
output: outputOptions,
watch: options.rollup.watch,
});
watcher.on("event", ({ code, error, result, duration }) => {
if (code === "ERROR") formatRollupLog(error);
if (code === "BUNDLE_START") console.info(`${label}: bundling...`);
if (code === "BUNDLE_END") {
console.info(
`${label}: bundled in ${secondsFormatter.format(duration / 1000)}.`,
);
}
if (result) result.close();
});
result = watcher;
} else {
bundle = await rollup(inputOptions);
result = await bundle.write(outputOptions);
await bundle.close();
}
} catch (error) {
if (options.caller === "cli") console.error(error);
if (bundle) await bundle.close();
result = { error };
}
console.timeEnd(label);
return result;
};
bundle.description = `Bundle dependencies for development or production.`;
export default bundle;