forked from lydell/LinkHints
-
Notifications
You must be signed in to change notification settings - Fork 0
/
rollup.config.js
334 lines (312 loc) · 9.04 KB
/
rollup.config.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
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
import commonjs from "@rollup/plugin-commonjs";
import resolve from "@rollup/plugin-node-resolve";
import replace from "@rollup/plugin-replace";
import sucrase from "@rollup/plugin-sucrase";
import fs from "fs";
import optionalRequireImport from "optional-require";
import path from "path";
import prettier from "rollup-plugin-prettier";
// eslint-disable-next-line import/no-extraneous-dependencies
import register from "sucrase/dist/register";
const jsx = {
jsxPragma: "h",
jsxFragmentPragma: "Fragment",
};
register.addHook(".ts", {
transforms: ["typescript", "imports"],
});
register.addHook(".tsx", {
transforms: ["typescript", "jsx", "imports"],
...jsx,
});
const transformCSS = require("./src/css").default;
const config = require("./project.config").default;
const optionalRequire = optionalRequireImport(require);
const customConfig = optionalRequire("./custom.config") || {};
const PROD = config.prod;
/** @type {{ DEFAULT_LOG_LEVEL: string, DEFAULT_STORAGE_SYNC: unknown }} */
const { DEFAULT_LOG_LEVEL = "log", DEFAULT_STORAGE_SYNC = null } = PROD
? {}
: customConfig;
setup();
const main = [
js(config.background),
js(config.worker),
js(config.renderer),
js(config.popup),
js(config.options),
template(config.manifest),
template(config.iconsCompilation),
html({
title: `${config.meta.name} Popup`,
html: config.popupHtml,
js: [config.popup.output],
css: [config.popupCss.output],
}),
css(config.popupCss),
html({
title: `${config.meta.name} Options`,
html: config.optionsHtml,
// Content scripts don’t run in the options page, so manually include them.
js: [config.worker.output, config.renderer.output, config.options.output],
css: [config.optionsCss.output],
}),
css(config.optionsCss),
config.needsPolyfill ? copy(config.polyfill) : undefined,
].flatMap((entry) =>
entry === undefined
? []
: {
...entry,
input: `${config.src}/${entry.input}`,
output:
typeof entry.output === "object" && !Array.isArray(entry.output)
? {
...entry.output,
file: `${config.compiled}/${entry.output.file}`,
indent: false,
}
: entry.output,
}
);
const docs = [
css(config.docs.sharedCss),
template(config.docs.index),
css(config.docs.indexCss),
template(config.docs.tutorial),
css(config.docs.tutorialCss),
].map((entry) => ({
...entry,
input: `${config.docs.src}/${entry.input}`,
output:
typeof entry.output === "object" && !Array.isArray(entry.output)
? {
...entry.output,
file: `${config.docs.compiled}/${entry.output.file}`,
indent: false,
}
: entry.output,
}));
/** * @type {Array<import("rollup").RollupOptions>} */
const all = main.concat(docs);
module.exports = all;
/**
* @returns {void}
*/
function setup() {
console.time("setup");
fs.rmSync(config.compiled, { recursive: true, force: true });
fs.rmSync(config.docs.compiled, { recursive: true, force: true });
copyDir(
`${config.src}/${config.iconsDir}`,
`${config.compiled}/${config.iconsDir}`
);
copyDir(
`${config.docs.src}/${config.docs.iconsDir}`,
`${config.docs.compiled}/${config.docs.iconsDir}`
);
console.timeEnd("setup");
}
/**
* @param {string} fromDir
* @param {string} toDir
* @returns {void}
*/
function copyDir(fromDir, toDir) {
fs.mkdirSync(toDir, { recursive: true });
for (const item of fs.readdirSync(fromDir, { withFileTypes: true })) {
if (item.isFile()) {
fs.copyFileSync(
path.join(fromDir, item.name),
path.join(toDir, item.name)
);
} else if (item.isDirectory()) {
copyDir(path.join(fromDir, item.name), path.join(toDir, item.name));
} else {
throw new Error(`copyDir: Neither a file nor a directory: ${item.name}`);
}
}
}
/**
* @param {{ input: string, output: string }} options
* @returns {import("rollup").RollupOptions}
*/
function js({ input, output }) {
return {
input,
output: {
file: output,
format: "iife",
sourcemap: !PROD,
externalLiveBindings: false,
},
plugins: [
replace({ ...makeGlobals(), preventAssignment: false }),
sucrase({
exclude: ["node_modules/**"],
transforms: ["typescript", "jsx"],
disableESTransforms: true,
// Don't add `__self` and `__source` to JSX, which Preact does not support.
production: true,
...jsx,
}),
resolve(),
commonjs(),
PROD ? prettier({ parser: "babel" }) : undefined,
].filter((plugin) => plugin !== undefined),
onwarn: (warning) => {
throw warning;
},
};
}
/**
* `input` must be a JavaScript file containing:
*
* export default data => compile(data)
*
* The function must return a string, and may optionally use `data`. Whatever
* string is returned will end up in `output`.
*
* @param {{ input: string, output: string, data?: unknown }} options
* @returns {import("rollup").RollupOptions}
*/
function template({ input, output, data }) {
/** @type {string | undefined} */
let content = undefined;
return {
input,
output: {
file: output,
format: "es",
},
treeshake: false,
plugins: [
sucrase({
transforms: ["typescript", "jsx"],
disableESTransforms: true,
production: true,
...jsx,
}),
resolve(),
commonjs(),
{
name: "template",
load: (id) => {
if (content === undefined) {
const dir = path.dirname(id);
for (const key of Object.keys(require.cache)) {
if (key.startsWith(dir)) {
delete require.cache[key];
}
}
content = require(id).default(data);
}
return null;
},
renderChunk: () => {
const chunk = { code: content ?? "", map: undefined };
content = undefined;
return chunk;
},
},
],
};
}
/**
* @param {{
* title: string,
* html: string,
* js: Array<string>,
* css: Array<string>,
* }} files
* @returns {import("rollup").RollupOptions}
*/
function html(files) {
return template({
input: "html.tsx",
output: files.html,
data: {
title: files.title,
polyfill: config.needsPolyfill
? path.relative(path.dirname(files.html), config.polyfill.output)
: undefined,
js: files.js.map((src) => path.relative(path.dirname(files.html), src)),
css: files.css.map((href) =>
path.relative(path.dirname(files.html), href)
),
},
});
}
/**
* @param {{ input: string, output: string }} options
* @param {(content: string) => string} [transform]
* @returns {import("rollup").RollupOptions}
*/
function copy({ input, output }, transform = (content) => content) {
let content = "";
return {
input,
output: {
file: output,
format: "es",
},
treeshake: false,
plugins: [
{
name: "copy",
load: (id) => {
content = transform(fs.readFileSync(id, "utf8"));
return "0";
},
renderChunk: () => ({ code: content, map: undefined }),
},
],
};
}
/**
* @param {{ input: string, output: string }} options
* @returns {import("rollup").RollupOptions}
*/
function css({ input, output }) {
return copy({ input, output }, transformCSS);
}
/**
* @returns {Record<string, string>}
*/
function makeGlobals() {
return {
BROWSER:
config.browser === undefined
? `(navigator.userAgent.includes("Firefox") ? "firefox" : "chrome")`
: JSON.stringify(config.browser),
// Note: BUILD_ID might vary between different files.
BUILD_ID: JSON.stringify(
PROD ? config.meta.version.replace(/\W/g, "_") : Date.now().toString()
),
COLOR_BADGE: JSON.stringify(config.colors.badge),
COLOR_GREEN: JSON.stringify(config.colors.green),
COLOR_PURPLE: JSON.stringify(config.colors.purple),
COLOR_YELLOW: JSON.stringify(config.colors.yellow),
DEFAULT_LOG_LEVEL_CONFIG: JSON.stringify(DEFAULT_LOG_LEVEL),
DEFAULT_STORAGE_SYNC: JSON.stringify(DEFAULT_STORAGE_SYNC),
META_HOMEPAGE: JSON.stringify(config.meta.homepage),
META_ICON: JSON.stringify(config.meta.icon),
META_NAME: JSON.stringify(config.meta.name),
META_SLUG: JSON.stringify(config.meta.slug),
META_TUTORIAL: JSON.stringify(config.meta.tutorial),
META_VERSION: JSON.stringify(config.meta.version),
PROD: JSON.stringify(PROD),
// Performance.
" instanceof Text": "?.nodeType === 3",
" instanceof HTMLAnchorElement": '?.localName === "a"',
" instanceof HTMLInputElement": '?.localName === "input"',
// Silence the “Unsafe assignment to innerHTML” warning from `web-ext lint`.
// This piece of code comes from Preact. Note that this disables the
// `dangerouslySetInnerHTML` feature.
"l.innerHTML": "l.__disabled__innerHTML",
// Hacks to make `preact-shadow-root` work with Preact 10.
"this.base&&this.base.parentNode": "this.__P",
"o.children[0],": "o.children,",
"this.shadow.firstChild": "undefined",
};
}