-
Notifications
You must be signed in to change notification settings - Fork 2.9k
Expand file tree
/
Copy pathwebpack-resources.js
More file actions
338 lines (299 loc) · 10.1 KB
/
Copy pathwebpack-resources.js
File metadata and controls
338 lines (299 loc) · 10.1 KB
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
// @ts-check
/**
* @typedef {import("webpack").Configuration} WebpackConfig
* @typedef {WebpackConfig & { devServer?: object }} WebpackServeConfig
* @typedef {import("webpack").ModuleOptions} WebpackModule
* @typedef {import("webpack").Configuration['output']} WebpackOutput
*/
/** */
const webpack = require('webpack');
const path = require('path');
const fs = require('fs');
/** @type {(c1: Partial<WebpackServeConfig>, c2: Partial<WebpackServeConfig>) => WebpackServeConfig} */
const merge = require('../tasks/merge');
const ForkTsCheckerWebpackPlugin = require('fork-ts-checker-webpack-plugin');
const getResolveAlias = require('./getResolveAlias');
const { findGitRoot } = require('../monorepo/index');
// @ts-ignore
const webpackVersion = require('webpack/package.json').version;
const getDefaultEnvironmentVars = require('./getDefaultEnvironmentVars');
console.log(`Webpack version: ${webpackVersion}`);
const gitRoot = findGitRoot();
const cssRule = {
test: /\.css$/,
include: /node_modules/,
use: ['style-loader', 'css-loader'],
};
/**
* As of webpack 5, you have to add the `es5` target for IE 11 compatibility.
* Otherwise it will output lambdas for smaller bundle size.
* https://webpack.js.org/migrate/5/#need-to-support-an-older-browser-like-ie-11
*/
const target = ['web', 'es5'];
module.exports = {
webpack,
/** Get the list of node_modules directories where loaders should be resolved */
getResolveLoaderDirs: () => [
'node_modules',
path.resolve(__dirname, '../node_modules'),
path.resolve(__dirname, '../../node_modules'),
],
/**
* @param {string} bundleName - Name for the bundle file. Usually either the unscoped name, or
* the scoped name with a - instead of / between the parts.
* @param {boolean} isProduction - whether it's a production build.
* @param {Partial<WebpackConfig>} customConfig - partial custom webpack config, merged into each full config object.
* @param {boolean} [onlyProduction] - whether to only generate the production config.
* @param {boolean} [excludeSourceMaps] - whether to skip generating source maps.
* @param {boolean} [profile] - whether to profile the bundle using webpack-bundle-analyzer.
* @returns {WebpackConfig[]} array of configs.
*/
createConfig(bundleName, isProduction, customConfig, onlyProduction, excludeSourceMaps, profile) {
const packageName = path.basename(process.cwd());
/** @type {WebpackModule} */
const module = {
noParse: [/autoit.js/],
rules: excludeSourceMaps
? [cssRule]
: [
{
test: /\.js$/,
use: 'source-map-loader',
enforce: 'pre',
},
cssRule,
],
};
const devtool = 'cheap-module-source-map';
const configs = [];
if (!onlyProduction) {
configs.push(
merge(
{
mode: 'development',
output: {
filename: `[name].js`,
path: path.resolve(process.cwd(), 'dist'),
pathinfo: false,
},
module,
target,
devtool,
plugins: getPlugins(packageName, false),
},
customConfig,
),
);
}
if (isProduction) {
configs.push(
merge(
{
mode: 'production',
output: {
filename: `[name].min.js`,
path: path.resolve(process.cwd(), 'dist'),
},
module,
target,
devtool: excludeSourceMaps ? undefined : devtool,
plugins: getPlugins(packageName, true, profile),
},
customConfig,
),
);
}
for (let config of configs) {
config.resolveLoader = {
modules: [
'node_modules',
path.resolve(__dirname, '../node_modules'),
path.resolve(__dirname, '../../node_modules'),
],
};
}
return configs;
},
/**
* Creates a standard bundle config for a package.
* @param {object} options
* @param {string|WebpackOutput} options.output - If a string, name for the output varible.
* If an object, full custom `output` config.
* @param {string} [options.bundleName] - Name for the bundle file. Defaults to the package folder name
* (unscoped package name).
* @param {string} [options.entry] - custom entry if not `./lib/index.js`
* @param {boolean} [options.isProduction] - whether it's a production build.
* @param {boolean} [options.onlyProduction] - whether to generate the production config.
* @param {Partial<WebpackConfig>} [options.customConfig] - partial custom webpack config, merged into each full config object
* @returns {WebpackConfig[]}
*/
createBundleConfig(options) {
const {
output,
bundleName = path.basename(process.cwd()),
entry = './lib/index.js',
isProduction = process.argv.includes('--mode=production'),
onlyProduction = false,
customConfig = {},
} = options;
return module.exports.createConfig(
bundleName,
isProduction,
merge(
{
entry: {
[bundleName]: entry,
},
output:
typeof output === 'string'
? {
libraryTarget: 'var',
library: output,
}
: output,
externals: {
react: 'React',
'react-dom': 'ReactDOM',
},
resolve: {
alias: getResolveAlias(true /*useLib*/),
},
},
customConfig,
),
onlyProduction,
);
},
/**
* Create a standard serve config for a legacy demo app.
* Note that this assumes a base directory (for serving and output) of `dist/demo`.
* @param {Partial<WebpackServeConfig>} customConfig - partial custom webpack config, merged into the full config
* @param {string} [outputFolder] - output folder (package-relative) if not `dist/demo`
* @returns {WebpackServeConfig}
*/
createServeConfig(customConfig, outputFolder = 'dist/demo') {
const outputPath = path.join(process.cwd(), outputFolder);
return merge(
{
devServer: {
// As of Webpack 5, this will open the browser at 127.0.0.1 by default
host: 'localhost',
port: 4322,
static: outputPath,
},
mode: 'development',
output: {
filename: `[name].js`,
libraryTarget: 'umd',
path: outputPath,
},
resolve: {
extensions: ['.ts', '.tsx', '.js'],
},
resolveLoader: {
modules: module.exports.getResolveLoaderDirs(),
},
devtool: 'eval',
module: {
rules: [
cssRule,
{
test: [/\.tsx?$/],
use: {
loader: 'ts-loader',
options: {
experimentalWatchApi: true,
transpileOnly: true,
},
},
exclude: [/node_modules/, /\.scss.ts$/, /\.test.tsx?$/],
},
{
test: /\.scss$/,
enforce: 'pre',
exclude: [/node_modules/],
use: [
{
loader: '@microsoft/loader-load-themed-styles', // creates style nodes from JS strings
},
{
loader: 'css-loader', // translates CSS into CommonJS
options: {
esModule: false,
modules: true,
importLoaders: 2,
},
},
{
loader: 'postcss-loader',
options: {
postcssOptions: {
plugins: ['autoprefixer'],
},
},
},
{
loader: 'sass-loader',
},
],
},
],
},
plugins: [
...(process.env.TF_BUILD || process.env.SKIP_TYPECHECK ? [] : [new ForkTsCheckerWebpackPlugin()]),
...(process.env.TF_BUILD || process.env.LAGE_PACKAGE_NAME ? [] : [new webpack.ProgressPlugin({})]),
],
target,
},
customConfig,
);
},
/**
* Create a serve config for a package with a legacy demo app in the examples package at
* `packages/react-examples/src/some-package/demo/index.tsx`.
* Note that this assumes a base directory (for serving and output) of `dist/demo` and will
* include `react-app-polyfill/ie11` for IE 11 support.
* @returns {WebpackServeConfig}
*/
createLegacyDemoAppConfig() {
const packageName = path.basename(process.cwd());
const reactExamples = path.join(gitRoot, 'packages/react-examples');
const demoEntryInExamples = path.join(reactExamples, 'src', packageName, 'demo/index.tsx');
if (!fs.existsSync(demoEntryInExamples)) {
throw new Error(`${packageName} does not have a legacy demo app (expected location: ${demoEntryInExamples})`);
}
return module.exports.createServeConfig({
entry: {
'demo-app': ['react-app-polyfill/ie11', demoEntryInExamples],
},
output: {
path: path.join(process.cwd(), 'dist/demo'),
filename: 'demo-app.js',
},
resolve: {
// Use the aliases for react-examples since the examples and demo may depend on some things
// that the package itself doesn't (and it will include the aliases for all the package's deps)
alias: getResolveAlias(false /*useLib*/, reactExamples),
fallback: {
path: require.resolve('path-browserify'),
},
},
});
},
};
function getPlugins(bundleName, isProduction, profile) {
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
const plugins = [new webpack.DefinePlugin(getDefaultEnvironmentVars(isProduction))];
if (isProduction && profile) {
plugins.push(
new BundleAnalyzerPlugin({
analyzerMode: 'static',
reportFilename: bundleName + '.stats.html',
openAnalyzer: false,
generateStatsFile: false,
logLevel: 'warn',
}),
);
}
return plugins;
}