-
Notifications
You must be signed in to change notification settings - Fork 36
/
javascript.js
231 lines (205 loc) · 6.16 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
const chalk = require('chalk');
const fs = require('fs-extra');
const gulp = require('gulp');
const gzipSize = require('gzip-size');
const path = require('path');
const {rollup} = require('rollup');
const babel = require('rollup-plugin-babel');
const commonjs = require('rollup-plugin-commonjs');
const resolve = require('rollup-plugin-node-resolve');
const replace = require('rollup-plugin-replace');
const terserRollupPlugin = require('rollup-plugin-terser').terser;
const {addAsset} = require('./utils/assets');
const {checkModuleDuplicates} = require('./utils/check-module-duplicates');
const {ENV} = require('./utils/env');
const config = require('../config.json');
/**
* A Rollup plugin to generate a list of import dependencies for each entry
* point in the module graph. This is then used by the template to generate
* the necessary `<link rel="modulepreload">` tags.
* @return {Object}
*/
const modulepreloadPlugin = () => {
return {
name: 'modulepreload',
generateBundle(options, bundle) {
// A mapping of entry chunk names to their full dependency list.
const modulepreloadMap = {};
// Loop through all the chunks to detect entries.
for (const [fileName, chunkInfo] of Object.entries(bundle)) {
if (chunkInfo.isEntry || chunkInfo.isDynamicEntry) {
modulepreloadMap[chunkInfo.name] = [fileName, ...chunkInfo.imports];
}
}
fs.outputJsonSync(
path.join(config.publicDir, 'modulepreload.json'),
modulepreloadMap, {spaces: 2});
},
};
};
/**
* A Rollup plugin that will fail the build it two chunks are detected with
* the same name. This is to avoid the issue described here (and need to be
* used until it's resolved):
* https://github.com/rollup/rollup/issues/3060#issuecomment-522719783
* @return {Object}
*/
const checkDuplicateChunksPlugin = () => {
return {
name: 'manifest',
generateBundle(options, bundle) {
const chunkNames = new Set();
for (const chunkInfo of Object.values(bundle)) {
const name = chunkInfo.name;
if (chunkNames.has(name)) {
throw new Error(`Duplicate chunk name '${name}' detected`);
}
chunkNames.add(name);
}
},
};
};
/**
* A Rollup plugin that adds each chunk to the asset manifest, keyed by
* the chunk name and the output extension, mapping to the file name.
* @return {Object}
*/
const manifestPlugin = () => {
return {
name: 'manifest',
generateBundle(options, bundle) {
const ext = path.extname(options.entryFileNames);
for (const [fileName, chunkInfo] of Object.entries(bundle)) {
addAsset(chunkInfo.name + ext, fileName);
}
},
};
};
const reportBundleSizePlugin = () => {
let entryNames;
return {
name: 'bundle-size-plugin',
buildStart: (inputOptions) => {
entryNames = Object.keys(inputOptions.input);
},
generateBundle: (options, bundle) => {
let bundleSize = 0;
for (const [filename, chunkInfo] of Object.entries(bundle)) {
const chunkSize = gzipSize.sync(chunkInfo.code);
bundleSize += chunkSize;
console.log(
chalk.magenta(String(chunkSize).padStart(6)),
chalk.gray(filename));
}
console.log(
chalk.yellow(String(bundleSize).padStart(6)),
chalk.white(`(total '${entryNames.join('/')}' bundle size)`));
},
};
};
const terserConfig = {
mangle: {
toplevel: true,
// properties: {
// regex: /(^_|_$)/,
// },
safari10: true,
},
};
const 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);
return directories[directories.lastIndexOf('node_modules') + 1];
}
};
let moduleBundleCache;
const compileModuleBundle = async () => {
const plugins = [
resolve(),
commonjs(),
replace({
'process.env.NODE_ENV': JSON.stringify(ENV),
}),
checkDuplicateChunksPlugin(),
modulepreloadPlugin(),
reportBundleSizePlugin(),
manifestPlugin(),
];
if (ENV !== 'development') {
plugins.push(terserRollupPlugin(terserConfig));
}
const bundle = await rollup({
input: {
'main-module': 'assets/javascript/main-module.js',
},
cache: moduleBundleCache,
plugins,
manualChunks,
preserveSymlinks: true, // Needed for `file:` entries in package.json.
treeshake: {
pureExternalModules: true,
},
});
moduleBundleCache = bundle.cache;
checkModuleDuplicates(bundle.cache.modules.map((m) => m.id));
await bundle.write({
dir: config.publicStaticDir,
format: 'esm',
chunkFileNames: '[name]-[hash].mjs',
entryFileNames: '[name]-[hash].mjs',
// Don't rewrite dynamic import when developing (for easier debugging).
dynamicImportFunction: ENV === 'development' ? undefined : '__import__',
});
};
let nomoduleBundleCache;
const compileClassicBundle = async () => {
const plugins = [
resolve(),
commonjs(),
replace({
'process.env.NODE_ENV': JSON.stringify(ENV),
}),
babel({
exclude: [
/core-js/,
/regenerator-runtime/,
],
presets: [['@babel/preset-env', {
targets: {browsers: ['ie 11']},
useBuiltIns: 'usage',
// debug: true,
loose: true,
corejs: 3,
}]],
plugins: ['@babel/plugin-syntax-dynamic-import'],
}),
reportBundleSizePlugin(),
manifestPlugin(),
];
if (ENV !== 'development') {
plugins.push(terserRollupPlugin(terserConfig));
}
const bundle = await rollup({
input: {
'main-nomodule': 'assets/javascript/main-nomodule.js',
},
cache: nomoduleBundleCache,
plugins,
inlineDynamicImports: true, // Need for a single output bundle.
preserveSymlinks: true, // Needed for `file:` entries in package.json.
});
nomoduleBundleCache = bundle.cache;
await bundle.write({
dir: config.publicStaticDir,
format: 'iife',
entryFileNames: '[name]-[hash].js',
});
};
gulp.task('javascript', async () => {
await compileModuleBundle();
if (ENV !== 'development') {
await compileClassicBundle();
}
});