-
Notifications
You must be signed in to change notification settings - Fork 36
/
javascript.js
251 lines (230 loc) · 6.44 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
/* eslint-disable no-console */
const gulp = require('gulp');
const path = require('path');
const {rollup} = require('rollup');
const babel = require('rollup-plugin-babel');
const replace = require('rollup-plugin-replace');
const resolve = require('rollup-plugin-node-resolve');
const terserRollupPlugin = require('rollup-plugin-terser').terser;
const TerserWebpackPlugin = require('terser-webpack-plugin');
const webpack = require('webpack');
const ManifestPlugin = require('webpack-manifest-plugin');
const {addAsset, getManifest} = require('./utils/assets');
const {checkModuleDuplicates} = require('./utils/check-module-duplicates.js');
const config = require('../config.json');
const minifyNameCache = {};
const webpackBuildCache = {};
const getEnv = () => {
return process.env.NODE_ENV || 'development';
};
const initPlugins = () => {
return [
// Identify each module by a hash, so caching is more predictable.
new webpack.HashedModuleIdsPlugin(),
// Create manifest of the original filenames to their hashed filenames.
new ManifestPlugin({
seed: getManifest(),
fileName: config.manifestFileName,
generate: (seed, files) => {
return files.reduce((manifest, opts) => {
// Needed until this issue is resolved:
// https://github.com/danethurber/webpack-manifest-plugin/issues/159
const unhashedName = path.basename(opts.path)
.replace(/[_.-][0-9a-f]{10}/, '');
addAsset(unhashedName, opts.path);
return getManifest();
}, seed);
},
}),
// Allows minifiers to removed dev-only code.
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify(getEnv()),
}),
];
};
const generateBabelEnvLoader = (targets) => {
return {
test: /\.m?js$/,
use: {
loader: 'babel-loader',
options: {
babelrc: false,
presets: [
['@babel/env', {
// debug: true,
modules: false,
useBuiltIns: 'entry',
targets,
}],
],
},
},
};
};
const baseConfig = () => ({
mode: getEnv() === 'development' ? 'development' : 'production',
plugins: initPlugins(),
devtool: '#source-map',
cache: webpackBuildCache,
});
const getMainConfig = () => Object.assign(baseConfig(), {
entry: {
'main': './assets/javascript/main.js',
},
output: {
path: path.resolve(__dirname, '..', config.publicStaticDir),
publicPath: '/',
filename: '[name]-[chunkhash:10].mjs',
},
module: {
rules: [
generateBabelEnvLoader({
browsers: [
// The last two versions of each browser, excluding versions
// that don't support <script type="module">.
'last 2 Chrome versions', 'not Chrome < 60',
'last 2 Safari versions', 'not Safari < 10.1',
'last 2 iOS versions', 'not iOS < 10.3',
'last 2 Firefox versions', 'not Firefox < 60',
'last 2 Edge versions', 'not Edge < 16',
]
}),
],
},
optimization: {
runtimeChunk: 'single',
splitChunks: {
chunks: 'all',
maxInitialRequests: Infinity,
minSize: 0,
cacheGroups: {
npm: {
test: /node_modules/,
name: (mod) => {
const pkgName = mod.context.match(/node_modules\/([^/]+)/)[1];
return `npm.${pkgName}`;
},
},
},
},
minimizer: [new TerserWebpackPlugin({
test: /\.m?js$/,
parallel: false, // Needed for cross-file prop mangling.
sourceMap: true,
terserOptions: {
mangle: {
properties: {
reserved: ['__e', '__esModule'],
regex: /(^_|_$)/,
},
},
nameCache: minifyNameCache, // Needed for cross-file prop mangling.
safari10: true,
},
})],
},
});
const getLegacyConfig = () => Object.assign(baseConfig(), {
entry: {
'main': './assets/javascript/main-legacy.js',
},
output: {
path: path.resolve(__dirname, '..', config.publicStaticDir),
publicPath: '/',
filename: '[name]-[chunkhash:10].es5.js',
},
module: {
rules: [
generateBabelEnvLoader({browsers: ['last 2 versions']}),
],
},
optimization: {
minimizer: [new TerserWebpackPlugin({
test: /\.m?js$/,
sourceMap: true,
terserOptions: {
// Don't mangle properties in legacy config
// because it breaks polyfills.
mangle: true,
safari10: true,
},
})],
},
});
const createCompiler = (config) => {
const compiler = webpack(config);
return () => {
return new Promise((resolve, reject) => {
compiler.run((err, stats) => {
if (err) return reject(err);
console.log(stats.toString({
colors: true,
// Uncomment to see all bundled modules.
// maxModules: Infinity,
}));
resolve();
});
});
};
};
gulp.task('javascript:main', async () => {
try {
const compileMainBundle = createCompiler(getMainConfig());
await compileMainBundle();
console.log(minifyNameCache);
if (getEnv() !== 'development') {
// Generate the main-legacy bundle.
const compileLegacyBundle = createCompiler(getLegacyConfig());
await compileLegacyBundle();
}
} catch (err) {
console.error(err);
}
});
gulp.task('javascript:sw', async () => {
try {
const plugins = [
resolve(),
replace({
'process.env.NODE_ENV': JSON.stringify(getEnv()),
}),
babel({
presets: [['@babel/env', {
// debug: true,
modules: false,
// useBuiltIns: true,
targets: {
browsers: [
'last 2 Chrome versions', 'not Chrome < 45',
'last 2 Firefox versions', 'not Firefox < 44',
'last 2 Edge versions', 'not Edge < 17',
'last 2 Safari versions', 'not Safari < 11.1',
],
},
}]],
}),
];
if (getEnv() !== 'development') {
plugins.push(terserRollupPlugin({
mangle: {
properties: {
regex: /(^_|_$)/,
},
},
}));
}
const bundle = await rollup({
input: 'assets/sw/sw.js',
plugins,
});
checkModuleDuplicates(bundle.modules.map((m) => m.id));
await bundle.write({
file: 'build/sw.js',
sourcemap: true,
format: 'es',
});
} catch (err) {
console.error(err);
}
});
gulp.task('javascript', gulp.series('javascript:main', 'javascript:sw'));