forked from ppy/osu-web
-
Notifications
You must be signed in to change notification settings - Fork 0
/
webpack.unmix.js
358 lines (317 loc) · 9.54 KB
/
webpack.unmix.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
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the GNU Affero General Public License v3.0.
// See the LICENCE file in the repository root for full licence text.
'use strict';
// built-in imports
const fs = require('fs');
const path = require('path');
const Autoprefixer = require('autoprefixer');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const CopyPlugin = require('copy-webpack-plugin');
const CssMinimizerPlugin = require('css-minimizer-webpack-plugin');
const dotenv = require('dotenv');
const ForkTsCheckerWebpackPlugin = require('fork-ts-checker-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const TerserPlugin = require('terser-webpack-plugin');
const TsconfigPathsPlugin = require('tsconfig-paths-webpack-plugin');
const webpack = require('webpack');
const SentryPlugin = require('webpack-sentry-plugin');
// #region env
const env = process.env.NODE_ENV || 'development';
dotenv.config({ path: `.env.${env}` });
dotenv.config();
const inProduction = env === 'production' || process.argv.includes('-p');
const writeManifest = !(process.env.SKIP_MANIFEST === '1'
|| process.env.SKIP_MANIFEST === 'true'
|| process.env.SKIP_MANIFEST);
// #endregion
// #region helpers
// Most plugins should follow webpack's own interpolation format:
// https://github.com/webpack/loader-utils#interpolatename
function outputFilename(name, ext = '[ext]', hashType = 'contenthash:8') {
return `${name}.[${hashType}].${ext}`;
}
function resolvePath(...segments) {
return path.resolve(__dirname, ...segments);
}
// #endregion
// #region Custom plugins
// Custom manifest dumper
// Dumps a manifest file for hashless asset name lookups outside of webpack.
// Uses asset name only unlike webpack-manifest-plugin which prefers chunk name first.
// webpack-assets-manifest is better but doesn't include assets from copy-webpack-plugin
// https://github.com/webdeveric/webpack-assets-manifest/issues/49
class Manifest {
constructor(options = {}) {
this.fileName = options.fileName;
}
apply(compiler) {
compiler.hooks.afterEmit.tap({ name: 'Manifest' }, (compilation) => {
const json = compilation.getStats().toJson({
// Disable data generation of everything we don't use
all: false,
// Add asset Information
assets: true,
// Show cached assets (setting this to `false` only shows emitted files)
cachedAssets: true,
});
const manifest = {};
json.assets.forEach((asset) => {
let name = asset.name;
if (!(name.startsWith('js/') || name.startsWith('css/'))) return;
if (name.endsWith('.map')) return;
// remove hash from name.
if (name.lastIndexOf('?') > 0) {
// querystring version
name = name.substring(0, name.lastIndexOf('?'));
} else {
// hash in filename version
const extname = path.extname(name);
let basename = name.substring(0, name.lastIndexOf(extname));
basename = basename.substring(0, basename.lastIndexOf('.'));
name = `${basename}${extname}`;
}
manifest[name] = path.join(compiler.options.output.publicPath, asset.name);
});
// directory might not exist when using webpack-dev-server because it
// doesn't write to the same location as the manifest file.
const dirname = path.dirname(this.fileName);
if (!fs.existsSync(dirname)) {
fs.mkdirSync(dirname, { recursive: true });
}
fs.writeFileSync(this.fileName, JSON.stringify(manifest, null, 2));
});
}
}
// #endregion
// #region entrypoints and output
const entry = {};
const entrypointDirs = [
'resources/css/entrypoints',
'resources/js/entrypoints',
];
const supportedExts = new Set(['.coffee', '.less', '.ts', '.tsx']);
for (const entrypointsPath of entrypointDirs) {
fs.readdirSync(resolvePath(entrypointsPath), { withFileTypes: true }).forEach((item) => {
if (item.isFile()) {
const filename = item.name;
const ext = path.extname(filename);
if (supportedExts.has(ext)) {
const entryName = path.basename(filename, ext);
if (entry[entryName] == null) {
entry[entryName] = [];
}
entry[entryName].push(resolvePath(entrypointsPath, filename));
}
}
});
}
const output = {
filename: outputFilename('js/[name]', 'js'),
path: resolvePath('public/assets'),
publicPath: '/assets/',
};
// #endregion
// #region plugin list
const plugins = [
new ForkTsCheckerWebpackPlugin(),
new webpack.ProvidePlugin({
$: 'jquery',
_: 'lodash',
d3: 'd3', // TODO: d3 is fat and probably should have it's own chunk
jQuery: 'jquery',
moment: 'moment',
React: 'react',
ReactDOM: 'react-dom',
Turbolinks: 'turbolinks',
}),
new webpack.DefinePlugin({
'process.env.DOCS_URL': JSON.stringify(process.env.DOCS_URL || 'https://docs.ppy.sh'),
}),
new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/), // don't add moment locales to bundle.
new MiniCssExtractPlugin({
filename: outputFilename('css/[name]', 'css'),
}),
new CopyPlugin({
patterns: [
{ from: 'resources/builds/locales', to: outputFilename('js/locales/[name]') },
{ from: 'node_modules/moment/locale', to: outputFilename('js/moment-locales/[name]') },
{ from: 'node_modules/@discordapp/twemoji/dist/svg/*-*.svg', to: 'images/flags/[name].[ext]' },
],
}),
];
if (writeManifest) {
plugins.push(new Manifest({ fileName: path.join(output.path, 'manifest.json') }));
}
// TODO: should have a different flag for this
if (!inProduction) {
// there is an issue (bug?) where assets loaded via file-loader don't show up in the stats
// when recompiling css so they end up being considered stale.
plugins.push(new CleanWebpackPlugin({ cleanStaleWebpackAssets: false }));
}
if (process.env.SENTRY_RELEASE === '1') {
plugins.push(
new SentryPlugin({
apiKey: process.env.SENTRY_API_KEY,
deleteAfterCompile: true,
exclude: /\.css(\.map)?$/,
filenameTransform(filename) {
return path.join('~', filename);
},
organisation: process.env.SENTRY_ORG,
project: process.env.SENTRY_PROJ,
release: process.env.GIT_SHA,
}),
);
}
const notifierConfigPath = resolvePath('.webpack-build-notifier-config.js');
if (fs.existsSync(notifierConfigPath)) {
const WebpackBuildNotifierPlugin = require('webpack-build-notifier');
plugins.push(new WebpackBuildNotifierPlugin(require(notifierConfigPath)));
}
// #endregion
// #region Loader rules
const rules = [
{
exclude: /node_modules/,
loader: 'ts-loader',
options: {
transpileOnly: true,
},
test: /\.tsx?$/,
},
{
test: /\.coffee$/,
use: ['coffee-loader'],
},
{
test: /\.less$/,
use: [
MiniCssExtractPlugin.loader,
{
loader: 'css-loader',
options: {
importLoaders: 1,
sourceMap: true,
},
},
{
loader: 'postcss-loader',
options: {
plugins: [Autoprefixer],
sourceMap: true,
},
},
{ loader: 'less-loader', options: { sourceMap: true } },
],
},
{
loaders: [
{
loader: 'file-loader',
options: {
name: outputFilename('images/[name]'),
},
},
{
loader: 'img-loader',
},
],
test: /(\.(png|jpe?g|gif|webp)$|^((?!font).)*\.svg$)/,
},
{
loader: 'file-loader',
options: {
name: outputFilename('fonts/[name]'),
},
test: /(\.(woff2?|ttf|eot|otf)$|font.*\.svg$)/,
},
];
// #endregion
// #region resolvers
const resolve = {
alias: {
'@fonts': path.resolve(__dirname, 'resources/fonts'),
'@images': path.resolve(__dirname, 'public/images'),
'ziggy-route': resolvePath('vendor/tightenco/ziggy/dist/index.es.js'),
},
extensions: ['*', '.js', '.coffee', '.ts', '.tsx'],
modules: [
resolvePath('resources/builds'),
resolvePath('resources/js'),
resolvePath('node_modules'),
],
plugins: [new TsconfigPathsPlugin()],
};
// #endregion
// #region optimization and chunk splitting settings
function partialPathCheck(pathCheck, partialPathArray) {
return pathCheck.includes(['', ...partialPathArray, ''].join(path.sep));
}
const docsOnlyLibraries = [
['node_modules', 'highlight.js'],
['node_modules', 'jets'],
];
const cacheGroups = {
commons: {
chunks: 'initial',
minChunks: 2,
name: 'commons',
priority: -20,
},
vendor: {
chunks: 'initial',
name: 'vendor',
priority: -10,
reuseExistingChunk: true,
// Doing it this way doesn't split the css imported via app.less from the main css bundle.
test: (module) => module.resource && (
partialPathCheck(module.resource, ['node_modules'])
&& docsOnlyLibraries.every((p) => !partialPathCheck(module.resource, p))
),
},
};
const optimization = {
moduleIds: 'hashed',
runtimeChunk: {
name: 'runtime',
},
splitChunks: {
cacheGroups,
},
};
if (inProduction) {
optimization.minimizer = [
new TerserPlugin({
sourceMap: true,
terserOptions: {
safari10: true,
},
}),
new CssMinimizerPlugin({
sourceMap: true,
}),
];
}
// #endregion
module.exports = {
devtool: 'source-map',
entry,
mode: inProduction ? 'production' : 'development',
module: {
rules,
},
optimization,
output,
plugins,
resolve,
stats: {
entrypoints: false,
errorDetails: false,
excludeAssets: [
// exclude copied files
/^js\/(moment-locales|locales)\//,
/^fonts/,
/^images/,
],
},
};