-
Notifications
You must be signed in to change notification settings - Fork 668
Expand file tree
/
Copy pathexecutor.ts
More file actions
183 lines (158 loc) · 5.24 KB
/
executor.ts
File metadata and controls
183 lines (158 loc) · 5.24 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
import { PromiseExecutor, logger } from '@nx/devkit';
import * as path from 'path';
import * as fs from 'fs';
import type { Configuration, Stats } from 'webpack';
import { BundleExecutorSchema } from './schema';
import { resolveProjectPath } from '../../utils/path-resolver';
const ERROR_MESSAGES = {
ENTRIES_EMPTY: 'entries must contain at least one entry point',
WEBPACK_NOT_FOUND:
'webpack is not installed. Add webpack as a dependency to the consuming project.',
WEBPACK_CONFIG_NOT_FOUND: (configPath: string) => `Webpack config not found: ${configPath}`,
WEBPACK_ERROR: (msg: string) => `Webpack build failed: ${msg}`,
} as const;
function loadWebpack(): typeof import('webpack') {
try {
return require('webpack');
} catch {
throw new Error(ERROR_MESSAGES.WEBPACK_NOT_FOUND);
}
}
function buildEntryMap(
entries: string[],
sourceDir: string,
mode: 'debug' | 'production',
): Record<string, string> {
const entryMap: Record<string, string> = {};
for (const entry of entries) {
const baseName = path.basename(entry, path.extname(entry));
const outputName = mode === 'debug' ? `${baseName}.debug` : baseName;
entryMap[outputName] = path.resolve(sourceDir, entry);
}
return entryMap;
}
function createWebpackConfig(
webpack: typeof import('webpack'),
baseConfig: Configuration,
entryMap: Record<string, string>,
outDir: string,
mode: 'debug' | 'production',
projectRoot: string,
): Configuration {
const config: Configuration = {
...baseConfig,
context: projectRoot,
entry: entryMap,
output: {
...(baseConfig.output || {}),
path: outDir,
filename: '[name].js',
},
};
config.optimization = {
...(config.optimization || {}),
minimize: false,
};
if (mode === 'debug') {
config.output = {
...(config.output || {}),
pathinfo: true,
};
config.devtool = 'eval-source-map';
}
const isInternalBuild =
String(process.env.BUILD_INTERNAL_PACKAGE).toLowerCase() === 'true'
|| String(process.env.BUILD_TEST_INTERNAL_PACKAGE).toLowerCase() === 'true';
if (isInternalBuild) {
const plugins = config.plugins ? [...config.plugins] : [];
plugins.push(
new webpack.NormalModuleReplacementPlugin(/(.*)\/license_validation/, (resource) => {
resource.request = resource.request.replace(
'license_validation',
'license_validation_internal',
);
}),
);
config.plugins = plugins;
}
return config;
}
function runWebpack(webpack: typeof import('webpack'), config: Configuration): Promise<Stats> {
return new Promise((resolve, reject) => {
webpack(config, (err, stats) => {
if (err) {
reject(err);
return;
}
if (!stats) {
reject(new Error('Webpack returned no stats'));
return;
}
if (stats.hasErrors()) {
const info = stats.toJson({ errors: true });
const errorMessages = (info.errors || []).map((e) => e.message).join('\n');
reject(new Error(errorMessages));
return;
}
resolve(stats);
});
});
}
const runExecutor: PromiseExecutor<BundleExecutorSchema> = async (options, context) => {
const projectRoot = resolveProjectPath(context);
const { entries, sourceDir, outDir, mode, webpackConfigPath = './webpack.config.js' } = options;
if (!entries?.length) {
logger.error(ERROR_MESSAGES.ENTRIES_EMPTY);
return { success: false };
}
const resolvedSourceDir = path.resolve(projectRoot, sourceDir);
const resolvedOutDir = path.resolve(projectRoot, outDir);
const resolvedConfigPath = path.resolve(projectRoot, webpackConfigPath);
let webpack: typeof import('webpack');
try {
webpack = loadWebpack();
} catch (error) {
const errorMsg = error instanceof Error ? error.message : String(error);
logger.error(errorMsg);
return { success: false };
}
if (!fs.existsSync(resolvedConfigPath)) {
logger.error(ERROR_MESSAGES.WEBPACK_CONFIG_NOT_FOUND(resolvedConfigPath));
return { success: false };
}
let baseConfig: Configuration;
try {
baseConfig = require(resolvedConfigPath);
} catch (error) {
const errorMsg = error instanceof Error ? error.message : String(error);
logger.error(`Failed to load webpack config: ${resolvedConfigPath} - ${errorMsg}`);
return { success: false };
}
const entryMap = buildEntryMap(entries, resolvedSourceDir, mode);
const config = createWebpackConfig(
webpack,
baseConfig,
entryMap,
resolvedOutDir,
mode,
projectRoot,
);
logger.verbose(`Bundling ${entries.length} entries in ${mode} mode`);
logger.verbose(`Source: ${resolvedSourceDir}`);
logger.verbose(`Output: ${resolvedOutDir}`);
try {
const stats = await runWebpack(webpack, config);
if (stats.hasWarnings()) {
const info = stats.toJson({ warnings: true });
(info.warnings || []).forEach((w) => logger.warn(w.message));
}
const assets = Object.keys(stats.compilation.assets);
logger.verbose(`Produced ${assets.length} bundle(s): ${assets.join(', ')}`);
return { success: true };
} catch (error) {
const errorMsg = error instanceof Error ? error.message : String(error);
logger.error(ERROR_MESSAGES.WEBPACK_ERROR(errorMsg));
return { success: false };
}
};
export default runExecutor;