-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjavascript.js
447 lines (377 loc) · 11.3 KB
/
javascript.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
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
/* eslint-disable no-console */
const path = require("path");
const gulp = require("gulp");
const { rollup, watch } = require("rollup");
const { babel } = require("@rollup/plugin-babel");
const replace = require("@rollup/plugin-replace");
const { nodeResolve } = require("@rollup/plugin-node-resolve");
const commonjs = require("@rollup/plugin-commonjs");
const externalGlobals = require("rollup-plugin-external-globals");
const { terser } = require("rollup-plugin-terser");
const postcss = require("rollup-plugin-postcss");
const genericNames = require("generic-names");
const csso = require("postcss-csso");
const postcssPresetEnv = require("postcss-preset-env");
const autoprefixer = require("autoprefixer");
const { bundleName } = require("./utils/rollup-plugin-bundle-name");
const config = require("../config.json");
const { ENV } = require("../env");
const {
DEVELOPMENT,
babelRuntimeVersion,
supportBrowsers,
} = require("./utils/constants");
const MODULE_NAME = "main-module";
const NOMODULE_NAME = "main-nomodule";
const reactAppGlobals = {
// react: "React",
// "react-dom": "ReactDOM",
// "react-router-dom": "ReactRouterDOM",
// `react-router-breadcrumbs-hoc` import from `react-router`,
// we redirect it to ReactRouterDOM since it's basically the same package
// "react-router": "ReactRouterDOM",
};
const reactAppExternal = Object.keys(reactAppGlobals);
const dotenvResult = require("dotenv").config({ debug: process.env.DEBUG });
// Replace every string that starts with `REPLACE_`
// with its corresponding env variable value
const envReplaceOptions = Object.entries(dotenvResult.parsed).reduce((acc, cur) => {
if (cur[0].startsWith("REPLACE_"))
acc[cur[0]] = cur[1];
return acc;
}, {});
const replaceOptions = Object.assign({
preventAssignment: true,
"process.env.NODE_ENV": JSON.stringify(ENV),
}, envReplaceOptions);
const cssModuleContext = path.resolve(__dirname, "app", "js");
const cssModuleScopedName = "[hash:base64:5]";
function baseBabelConfig({ nomodule = false }) {
const browsers = nomodule ? ["ie 11"] : supportBrowsers;
return {
presets: [
[
"@babel/preset-env",
{
targets: { browsers },
modules: false,
useBuiltIns: "usage",
// debug: true,
// loose: true,
corejs: 3,
},
],
[
"@babel/preset-react",
{
runtime: "automatic",
useBuiltIns: true,
useSpread: false,
},
],
],
plugins: [
["react-css-modules", {
context: cssModuleContext,
generateScopedName: cssModuleScopedName,
}],
"macros",
"transform-react-remove-prop-types",
"@babel/plugin-syntax-dynamic-import",
[
"@babel/plugin-transform-runtime",
{
// do NOT duplicate the `corejs` config here
regenerator: false,
useESModules: true,
version: `^${babelRuntimeVersion}`,
},
],
],
};
}
function baseRollupPlugins({ nomodule = false } = {}) {
const postcssPlugins = [];
if (ENV !== DEVELOPMENT) {
postcssPlugins.push(
postcssPresetEnv({
browsers: supportBrowsers.join(", "),
stage: 3,
features: {
"nesting-rules": true,
},
}),
autoprefixer({
overrideBrowserslist: supportBrowsers,
}),
csso,
);
}
const babelConfigForRollup = Object.assign({
exclude: [
/core-js/,
/regenerator-runtime/,
/node_modules/,
],
babelHelpers: "runtime", // @rollup/plugin-babel specific
}, baseBabelConfig({ nomodule }));
const plugins = [
postcss({
// TODO: extract to a css file with hashed name,
// inject css modules to <head> for now
extract: false,
inject: true,
plugins: postcssPlugins,
modules: {
// Special scoped name generation function used to sync
// babel-plugin-postcss-modules with rollup-plugin-postcss.
generateScopedName: (cssname, filepath) => {
// Generation logic basically adapted from here:
// https://github.com/gajus/babel-plugin-react-css-modules/blob/9fcb91f5c3d3b181d0087ab7de999ac2c9c1dd11/src/requireCssModule.js#L103-L109
const generate = genericNames(cssModuleScopedName, {
context: cssModuleContext,
});
return generate(cssname, filepath);
},
},
autoModules: false,
sourceMap: ENV === DEVELOPMENT,
}),
nodeResolve({
browser: true,
extensions: [".js", ".jsx"],
}),
replace(replaceOptions),
commonjs({
include: /node_modules/,
exclude: [
"node_modules/**/es?(m)/**",
// /\/core-js\//,
],
// https://github.com/rollup/plugins/tree/master/packages/commonjs#esmexternals
esmExternals: true,
requireReturnsDefault: "auto",
// include: "node_modules/**",
}),
babel(babelConfigForRollup),
bundleName({
name: nomodule ? NOMODULE_NAME : MODULE_NAME,
globalKey: nomodule ? "nomoduleBundleName" : "moduleBundleName",
}),
];
if (!nomodule) {
plugins.push(externalGlobals(reactAppGlobals));
}
if (ENV !== DEVELOPMENT) {
plugins.push(terser({
mangle: {
toplevel: true,
// properties: {
// regex: /(^_|_$)/,
// },
safari10: nomodule,
},
module: !nomodule,
}));
}
return plugins;
}
function manualChunks(id) {
if (id.includes("node_modules")) {
// The directory name following the last `node_modules`.
// Usually this is the package, but it could also be the scope.
const directories = id.split(path.sep);
const name = directories[directories.lastIndexOf("node_modules") + 1];
// Group react dependencies into a common "react" chunk.
// NOTE: This isn't strictly necessary for this app, but it's included
// as an example to show how to manually group common dependencies.
if (name.match(/^react$/) ||
["prop-types", "scheduler"].includes(name)) {
return "react";
}
// Group `tslib` and `dynamic-import-polyfill` into the default bundle.
// NOTE: This isn't strictly necessary for this app, but it's included
// to show how to manually keep deps in the default chunk.
if (name === "tslib" || name === "dynamic-import-polyfill") {
return;
}
if (name.match(/babel/) || name.match(/core-js/)) {
return "core-js";
}
// remove `@` from name
if (name.includes("@")) {
return name.replace(/@/g, "");
}
// Otherwise just return the name.
return name;
}
if (id.includes("js/utils")) {
return "utils";
}
if (id.includes("view/component")) {
return "component";
}
}
// ***************************************
// #region watch
let watchCache;
function watchFiles() {
const inputOptions = {
input: {
[MODULE_NAME]: `./app/js/${MODULE_NAME}.js`,
},
external: reactAppExternal,
plugins: baseRollupPlugins({ nomodule: false }),
cache: watchCache,
preserveEntrySignatures: false,
preserveSymlinks: true, // Needed for `file:` entries in package.json.
manualChunks,
};
const moduleOutputOptions = {
dir: config.publicStaticJsDir,
entryFileNames: "[name]-[hash].js", // prod build
chunkFileNames: "[name]-[hash].chunk.js", // prod build
format: "esm",
globals: reactAppGlobals,
// Don't rewrite dynamic import when developing (for easier debugging).
dynamicImportFunction: ENV === DEVELOPMENT ? undefined : "__import__",
};
if (ENV === DEVELOPMENT) {
moduleOutputOptions.entryFileNames = "[name].js";
moduleOutputOptions.chunkFileNames = "[name].chunk.js";
moduleOutputOptions.sourcemap = true;
}
try {
const watcher = watch({
...inputOptions,
output: [moduleOutputOptions],
watch: {
include: [
"app/js/**/*.js?(x)",
"app/js/**/*.css",
".env",
],
exclude: [
"node_modules/**",
],
clearScreen: false,
},
});
/* eslint-disable no-console */
watcher.on("event", ev => {
if (ev.code === "START") {
console.info("Start bundling...");
}
if (ev.code === "END") {
console.info("Bundling completed!");
}
if (ev.code === "BUNDLE_END") {
watchCache = ev.result.cache;
}
if (ev.code === "ERROR") {
console.error(ev.error);
}
});
}
catch (err) {
process.stdout.write("\x07");
// Log but don't throw so watching still works.
console.error(err);
}
}
// #endregion
// ***************************************
// #region bundle
let moduleBundleCache;
const compileModuleBundle = async () => {
const plugins = baseRollupPlugins({ nomodule: false });
const bundle = await rollup({
input: {
[MODULE_NAME]: `./app/js/${MODULE_NAME}.js`,
},
external: reactAppExternal,
plugins,
cache: moduleBundleCache,
preserveEntrySignatures: false,
preserveSymlinks: true, // Needed for `file:` entries in package.json.
manualChunks,
});
// eslint-disable-next-line require-atomic-updates
moduleBundleCache = bundle.cache;
const moduleOutputOptions = {
dir: config.publicStaticJsDir,
entryFileNames: "[name]-[hash].js", // prod build
chunkFileNames: "[name]-[hash].chunk.js", // prod build
format: "esm",
globals: reactAppGlobals,
// Don't rewrite dynamic import when developing (for easier debugging).
dynamicImportFunction: ENV === DEVELOPMENT ? undefined : "__import__",
};
if (ENV === DEVELOPMENT) {
moduleOutputOptions.entryFileNames = "[name].js";
moduleOutputOptions.chunkFileNames = "[name].chunk.js";
moduleOutputOptions.sourcemap = true;
}
await bundle.write(moduleOutputOptions);
};
let nomoduleBundleCache;
const compileClassicBundle = async () => {
const plugins = baseRollupPlugins({ nomodule: true });
const bundle = await rollup({
input: {
[NOMODULE_NAME]: `./app/js/${NOMODULE_NAME}.js`,
},
external: reactAppExternal,
cache: nomoduleBundleCache,
plugins,
inlineDynamicImports: true, // Need for a single output bundle.
preserveEntrySignatures: false,
preserveSymlinks: true, // Needed for `file:` entries in package.json.
});
// eslint-disable-next-line require-atomic-updates
nomoduleBundleCache = bundle.cache;
const nomoduleOptions = {
dir: config.publicStaticJsDir,
format: "iife",
entryFileNames: "[name]-[hash].js",
globals: reactAppGlobals,
};
// const { output } = await bundle.generate(nomoduleOptions);
// global.nomoduleBundleName = output[0].fileName;
await bundle.write(nomoduleOptions);
};
// #endregion
gulp.task("javascript", async () => {
try {
if (ENV !== DEVELOPMENT) {
await Promise.all([
compileModuleBundle(),
compileClassicBundle(),
]);
}
else {
await compileModuleBundle();
}
}
catch (err) {
// Beep!
process.stdout.write("\x07");
// Log but don't throw so watching still works.
console.error(err);
}
});
gulp.task("javascript:watch", async () => {
try {
watchFiles();
}
catch (err) {
// Beep!
process.stdout.write("\x07");
// Log but don't throw so watching still works.
console.error(err);
}
});
// export base babel config so lingui can use
module.exports = {
baseBabelConfig,
};