-
Notifications
You must be signed in to change notification settings - Fork 4k
/
builder.ts
166 lines (140 loc) · 4.38 KB
/
builder.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
import { spawnSync } from 'child_process';
import * as fs from 'fs';
import * as path from 'path';
import { findPkgPath } from './util';
/**
* Builder options
*/
export interface BuilderOptions {
/**
* Entry file
*/
readonly entry: string;
/**
* The output directory
*/
readonly outDir: string;
/**
* Expose modules as UMD under this name
*/
readonly global: string;
/**
* Minify
*/
readonly minify?: boolean;
/**
* Include source maps
*/
readonly sourceMaps?: boolean;
/**
* The cache directory
*/
readonly cacheDir?: string;
/**
* The node version to use as target for Babel
*/
readonly nodeVersion: string;
/**
* The docker tag of the node base image to use in the parcel-bundler docker image
*
* @see https://hub.docker.com/_/node/?tab=tags
*/
readonly nodeDockerTag: string;
/**
* The root of the project. This will be used as the source for the volume
* mounted in the Docker container.
*/
readonly projectRoot: string;
}
/**
* Builder
*/
export class Builder {
private readonly pkgPath: string;
private readonly originalPkg: Buffer;
private readonly originalPkgJson: { [key: string]: any };
constructor(private readonly options: BuilderOptions) {
// Original package.json
const pkgPath = findPkgPath();
if (!pkgPath) {
throw new Error('Cannot find a `package.json` in this project.');
}
this.pkgPath = path.join(pkgPath, 'package.json');
this.originalPkg = fs.readFileSync(this.pkgPath);
this.originalPkgJson = JSON.parse(this.originalPkg.toString());
}
/**
* Build with parcel in a Docker container
*/
public build(): void {
try {
this.updatePkg();
const dockerBuildArgs = [
'build',
'--build-arg', `NODE_TAG=${this.options.nodeDockerTag}`,
'-t', 'parcel-bundler',
path.join(__dirname, '../parcel-bundler'),
];
const build = spawnSync('docker', dockerBuildArgs);
if (build.error) {
throw build.error;
}
if (build.status !== 0) {
throw new Error(`[Status ${build.status}] stdout: ${build.stdout?.toString().trim()}\n\n\nstderr: ${build.stderr?.toString().trim()}`);
}
const containerProjectRoot = '/project';
const containerOutDir = '/out';
const containerCacheDir = '/cache';
const containerEntryPath = path.join(containerProjectRoot, path.relative(this.options.projectRoot, path.resolve(this.options.entry)));
const dockerRunArgs = [
'run', '--rm',
'-v', `${this.options.projectRoot}:${containerProjectRoot}`,
'-v', `${path.resolve(this.options.outDir)}:${containerOutDir}`,
...(this.options.cacheDir ? ['-v', `${path.resolve(this.options.cacheDir)}:${containerCacheDir}`] : []),
'-w', path.dirname(containerEntryPath),
'parcel-bundler',
];
const parcelArgs = [
'parcel', 'build', containerEntryPath,
'--out-dir', containerOutDir,
'--out-file', 'index.js',
'--global', this.options.global,
'--target', 'node',
'--bundle-node-modules',
'--log-level', '2',
!this.options.minify && '--no-minify',
!this.options.sourceMaps && '--no-source-maps',
...(this.options.cacheDir ? ['--cache-dir', containerCacheDir] : []),
].filter(Boolean) as string[];
const parcel = spawnSync('docker', [...dockerRunArgs, ...parcelArgs]);
if (parcel.error) {
throw parcel.error;
}
if (parcel.status !== 0) {
throw new Error(`[Status ${parcel.status}] stdout: ${parcel.stdout?.toString().trim()}\n\n\nstderr: ${parcel.stderr?.toString().trim()}`);
}
} catch (err) {
throw new Error(`Failed to build file at ${this.options.entry}: ${err}`);
} finally { // Always restore package.json to original
this.restorePkg();
}
}
/**
* Updates the package.json to configure Parcel
*/
private updatePkg() {
const updateData: { [key: string]: any } = {};
// Update engines.node (Babel target)
updateData.engines = { node: `>= ${this.options.nodeVersion}` };
// Write new package.json
if (Object.keys(updateData).length !== 0) {
fs.writeFileSync(this.pkgPath, JSON.stringify({
...this.originalPkgJson,
...updateData,
}, null, 2));
}
}
private restorePkg() {
fs.writeFileSync(this.pkgPath, this.originalPkg);
}
}