This repository has been archived by the owner on Jan 22, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 5
/
index.ts
304 lines (297 loc) · 12 KB
/
index.ts
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
import { removeEmpty } from "@pixeloven-core/common";
import { getUtils } from "@pixeloven-core/env";
import { resolveSourceRoot } from "@pixeloven-core/filesystem";
import { logger } from "@pixeloven-core/logger";
import tsLoader from "@pixeloven-webpack/ts-loader";
import CaseSensitivePathsPlugin from "case-sensitive-paths-webpack-plugin";
import CircularDependencyPlugin from "circular-dependency-plugin";
import MiniCssExtractPlugin from "mini-css-extract-plugin";
import TimeFixPlugin from "time-fix-plugin";
import webpack, { Configuration } from "webpack";
import ManifestPlugin from "webpack-manifest-plugin";
import { Options } from "./types";
import { getSetup } from "./helpers/shared";
function getConfig(options: Options) {
/**
* Utility functions to help segment configuration based on environment
*/
const { ifProduction, ifDevelopment, ifClient } = getUtils({
mode: options.mode,
name: options.name,
target: options.target,
});
const {
getDevTool,
getEntry,
getExternals,
getMode,
getModuleFileLoader,
getModuleSCSSLoader,
getNode,
getOptimization,
getOutput,
getPerformance,
getPluginBundleAnalyzer,
getPluginForkTsCheckerWebpack,
getResolve,
} = getSetup(options);
/**
* @todo eventually make this something that can be configurable once we understand it's impact more
*/
const limitCyclesDetected = 3;
let numCyclesDetected = 0;
let numCyclesDisplayed = 0;
/**
* @todo Look into https://github.com/mzgoddard/hard-source-webpack-plugin
*/
const plugins = ifClient(
removeEmpty([
/**
* Fixes a known issue with cross-platform differences in file watchers,
* so that webpack doesn't lose file changes when watched files change rapidly
* https://github.com/webpack/webpack-dev-middleware#known-issues
*
* @env development
*/
ifDevelopment(new TimeFixPlugin()),
/**
* Watcher doesn"t work well if you mistype casing in a path so we use
* a plugin that prints an error when you attempt to do this.
* See https://github.com/facebookincubator/create-react-app/issues/240
*
* @env development
*/
ifDevelopment(new CaseSensitivePathsPlugin()),
/**
* Allows for circular dependency detection
*
* @todo should determine why we can't just push errors/strings to compilation.warnings
*/
new CircularDependencyPlugin({
// exclude detection of files based on a RegExp
exclude: /node_modules/,
onStart() {
numCyclesDetected = 0;
numCyclesDisplayed = 0;
},
onDetected({ paths }) {
if (numCyclesDetected < limitCyclesDetected) {
// compilation.warnings.push(new Error(`circular dependency ${paths.join(" -> ")}`));
logger.warn(
`circular dependency ${paths.join(" -> ")}`,
);
numCyclesDisplayed++;
}
numCyclesDetected++;
},
onEnd() {
if (numCyclesDetected > limitCyclesDetected) {
// compilation.warnings.push(new Error(`${numCyclesDetected - numCyclesDisplayed} additional circular dependencies with a total of ${numCyclesDetected} detected`));
logger.warn(
`${numCyclesDetected -
numCyclesDisplayed} additional circular dependencies with a total of ${numCyclesDetected} detected`,
);
}
},
}),
/**
* Helps prevent hashes from updating if a bundle hasn't changed.
* @env all
*
* @todo should we use webpack.ids.DeterministicModuleIdsPlugin instead?
*/
new webpack.HashedModuleIdsPlugin(),
/**
* Moment.js is an extremely popular library that bundles large locale files
* by default due to how Webpack interprets its code. This is a practical
* solution that requires the user to opt into importing specific locales.
* @url https://github.com/jmblog/how-to-optimize-momentjs-with-webpack
* @env all
*/
new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/),
/**
* Does a string replacement for specific env variables
* @description Provides entry point specific env variables
* @env all
*/
new webpack.EnvironmentPlugin({
NAME: options.name,
PUBLIC_PATH: options.publicPath,
TARGET: options.target,
}),
/**
* Perform type checking and linting in a separate process to speed up compilation
* @env all
*/
getPluginForkTsCheckerWebpack(),
/**
* Extract css to file
* @env production
*/
new MiniCssExtractPlugin({
chunkFilename: ifProduction(
"static/css/[name].[id].[contenthash].css",
"static/css/[name].[id].[hash].css",
),
filename: ifProduction(
"static/css/[name].[contenthash].css",
"static/css/[name].[hash].css",
),
}),
getPluginBundleAnalyzer(options.stats),
/**
* Generate a manifest file which contains a mapping of all asset filenames
* to their corresponding output file so that tools can pick it up without
* having to parse `index.html`.
*
* @env production
*/
ifProduction(
new ManifestPlugin({
fileName: "asset-manifest.json",
}),
),
/**
* This is necessary to emit hot updates (currently CSS only):
*
* @env development
*/
ifDevelopment(new webpack.HotModuleReplacementPlugin()),
]),
removeEmpty([
/**
* Fixes a known issue with cross-platform differences in file watchers,
* so that webpack doesn't lose file changes when watched files change rapidly
* https://github.com/webpack/webpack-dev-middleware#known-issues
*
* @env development
*/
ifDevelopment(new TimeFixPlugin()),
/**
* Watcher doesn"t work well if you mistype casing in a path so we use
* a plugin that prints an error when you attempt to do this.
* See https://github.com/facebookincubator/create-react-app/issues/240
*
* @env development
*/
ifDevelopment(new CaseSensitivePathsPlugin()),
/**
* Allows for circular dependency detection
*
* @todo should determine why we can't just push errors/strings to compilation.warnings
*/
new CircularDependencyPlugin({
// exclude detection of files based on a RegExp
exclude: /node_modules/,
onStart() {
numCyclesDetected = 0;
numCyclesDisplayed = 0;
},
onDetected({ paths }) {
if (numCyclesDetected < limitCyclesDetected) {
// compilation.warnings.push(new Error(`circular dependency ${paths.join(" -> ")}`));
logger.warn(
`circular dependency ${paths.join(" -> ")}`,
);
numCyclesDisplayed++;
}
numCyclesDetected++;
},
onEnd() {
if (numCyclesDetected > limitCyclesDetected) {
// compilation.warnings.push(new Error(`${numCyclesDetected - numCyclesDisplayed} additional circular dependencies with a total of ${numCyclesDetected} detected`));
logger.warn(
`${numCyclesDetected -
numCyclesDisplayed} additional circular dependencies with a total of ${numCyclesDetected} detected`,
);
}
},
}),
/**
* Moment.js is an extremely popular library that bundles large locale files
* by default due to how Webpack interprets its code. This is a practical
* solution that requires the user to opt into importing specific locales.
* @url https://github.com/jmblog/how-to-optimize-momentjs-with-webpack
* @env all
*/
new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/),
/**
* Define environmental variables base on entry point
* @description Provides entry point specific env variables
*
* @env all
*/
new webpack.EnvironmentPlugin({
NAME: options.name,
PUBLIC_PATH: options.publicPath,
TARGET: options.target,
}),
getPluginBundleAnalyzer(options.stats),
getPluginForkTsCheckerWebpack(),
]),
);
/**
* Client side configuration
*/
return removeEmpty({
bail: ifProduction(),
devtool: getDevTool(),
entry: getEntry(),
externals: getExternals(),
mode: getMode(),
module: {
rules: [
{
oneOf: [
/**
* Sets express 4.x view to null. We use our own custom react renderer and have no use for this feature.
* Ideally express would make this modular but with this we can optimize express for SSR.
*
* @note Side effect is none of the features associated with express template rendering will work.
* https://expressjs.com/en/api.html#res.render
*/
{
test: /express\/lib\/view.js$/,
use: [
{
loader: require.resolve("null-loader"),
},
],
},
/**
* Allows us to handle mjs.
*/
{
test: /.mjs$/,
type: "javascript/auto",
use: [
{
loader: require.resolve("babel-loader"),
},
],
},
{
include: resolveSourceRoot(),
test: [/\.(js|jsx|mjs)$/, /\.(ts|tsx)$/],
use: tsLoader,
},
getModuleSCSSLoader(),
getModuleFileLoader(),
],
},
],
strictExportPresence: true,
},
name: options.name,
node: getNode(),
optimization: getOptimization(),
output: getOutput(),
performance: getPerformance(),
plugins,
profile: options.profiling,
resolve: getResolve(),
stats: "verbose",
target: options.target,
}) as Configuration;
}
export { getConfig, Options };