forked from callstack/react-native-builder-bob
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcompile.ts
297 lines (261 loc) · 8.38 KB
/
compile.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
import path from 'path';
import fs from 'fs-extra';
import kleur from 'kleur';
import * as babel from '@babel/core';
import glob from 'glob';
import type { Input } from '../types';
type Options = Input & {
esm?: boolean;
babelrc?: boolean | null;
configFile?: string | false | null;
sourceMaps?: boolean;
copyFlow?: boolean;
modules: 'commonjs' | 'preserve';
exclude: string;
jsxRuntime?: 'automatic' | 'classic';
};
const sourceExt = /\.([cm])?[jt]sx?$/;
export default async function compile({
root,
source,
output,
esm = false,
babelrc = false,
configFile = false,
exclude,
modules,
copyFlow,
sourceMaps = true,
report,
jsxRuntime = 'automatic',
}: Options) {
const files = glob.sync('**/*', {
cwd: source,
absolute: true,
nodir: true,
ignore: exclude,
});
report.info(
`Compiling ${kleur.blue(String(files.length))} files in ${kleur.blue(
path.relative(root, source)
)} with ${kleur.blue('babel')}`
);
const pkg = JSON.parse(
await fs.readFile(path.join(root, 'package.json'), 'utf-8')
);
if (copyFlow) {
if (!Object.keys(pkg.devDependencies || {}).includes('flow-bin')) {
report.warn(
`The ${kleur.blue(
'copyFlow'
)} option was specified, but couldn't find ${kleur.blue(
'flow-bin'
)} in ${kleur.blue(
'package.json'
)}.\nIf the project is using ${kleur.blue(
'flow'
)}, then make sure you have added ${kleur.blue(
'flow-bin'
)} to your ${kleur.blue(
'devDependencies'
)}, otherwise remove the ${kleur.blue('copyFlow')} option.`
);
}
}
await fs.mkdirp(output);
if (!esm) {
// Ideally we should code with ESM syntax as CommonJS if `esm` is not enabled
// This maintain compatibility with code written for CommonJS
// However currently NextJS has non-standard behavior and breaks this
// So for now we only set this conditionally
await fs.writeJSON(path.join(output, 'package.json'), {
type: modules === 'commonjs' ? 'commonjs' : 'module',
});
}
await Promise.all(
files.map(async (filepath) => {
const outputFilename = path
.join(output, path.relative(source, filepath))
.replace(sourceExt, '.$1js');
await fs.mkdirp(path.dirname(outputFilename));
if (!sourceExt.test(filepath)) {
// Copy files which aren't source code
fs.copy(filepath, outputFilename);
return;
}
const content = await fs.readFile(filepath, 'utf-8');
const result = await babel.transformAsync(content, {
cwd: root,
babelrc: babelrc,
configFile: configFile,
sourceMaps,
sourceRoot: path.relative(path.dirname(outputFilename), source),
sourceFileName: path.relative(source, filepath),
filename: filepath,
...(babelrc || configFile
? null
: {
presets: [
[
require.resolve('../../babel-preset'),
{
modules:
// If a file is explicitly marked as ESM, then preserve the syntax
/\.m[jt]s$/.test(filepath) ? 'preserve' : modules,
esm,
jsxRuntime,
},
],
],
}),
});
if (result == null) {
throw new Error('Output code was null');
}
let code = result.code;
if (sourceMaps && result.map) {
const mapFilename = outputFilename + '.map';
code += '\n//# sourceMappingURL=' + path.basename(mapFilename);
// Don't inline the source code, it can be retrieved from the source file
result.map.sourcesContent = undefined;
await fs.writeJSON(mapFilename, result.map);
}
await fs.writeFile(outputFilename, code);
if (copyFlow) {
fs.copy(filepath, outputFilename + '.flow');
}
})
);
report.success(`Wrote files to ${kleur.blue(path.relative(root, output))}`);
const getGeneratedEntryPath = async () => {
if (pkg.source) {
for (const ext of ['.js', '.cjs', '.mjs']) {
const indexName =
// The source field may not have an extension, so we add it instead of replacing directly
path.basename(pkg.source).replace(sourceExt, '') + ext;
const potentialPath = path.join(
output,
path.dirname(path.relative(source, path.join(root, pkg.source))),
indexName
);
if (await fs.pathExists(potentialPath)) {
return path.relative(root, potentialPath);
}
}
}
return null;
};
const fields =
modules === 'commonjs'
? [{ name: 'main', value: pkg.main }]
: [{ name: 'module', value: pkg.module }];
if (esm) {
if (modules === 'commonjs') {
fields.push(
typeof pkg.exports?.['.']?.require === 'string'
? {
name: "exports['.'].require",
value: pkg.exports?.['.']?.require,
}
: {
name: "exports['.'].require.default",
value: pkg.exports?.['.']?.require?.default,
}
);
} else {
fields.push(
typeof pkg.exports?.['.']?.import === 'string'
? {
name: "exports['.'].import",
value: pkg.exports?.['.']?.import,
}
: {
name: "exports['.'].import.default",
value: pkg.exports?.['.']?.import?.default,
}
);
}
} else {
if (modules === 'commonjs' && pkg.exports?.['.']?.require) {
report.warn(
`The ${kleur.blue('esm')} option is disabled, but the ${kleur.blue(
"exports['.'].require"
)} field is set in ${kleur.blue(
'package.json'
)}. This is likely a mistake.`
);
} else if (modules === 'preserve' && pkg.exports?.['.']?.import) {
report.warn(
`The ${kleur.blue('esm')} option is disabled, but the ${kleur.blue(
"exports['.'].import"
)} field is set in ${kleur.blue(
'package.json'
)}. This is likely a mistake.`
);
}
}
if (fields.some((field) => field.value)) {
await Promise.all(
fields.map(async ({ name, value }) => {
if (!value) {
return;
}
if (name.startsWith('exports') && value && !/^\.\//.test(value)) {
report.error(
`The ${kleur.blue(name)} field in ${kleur.blue(
`package.json`
)} should be a relative path starting with ${kleur.blue(
'./'
)}. Found: ${kleur.blue(value)}`
);
throw new Error(`Found incorrect path in '${name}' field.`);
}
try {
require.resolve(path.join(root, value));
} catch (e: unknown) {
if (
e != null &&
typeof e === 'object' &&
'code' in e &&
e.code === 'MODULE_NOT_FOUND'
) {
const generatedEntryPath = await getGeneratedEntryPath();
if (!generatedEntryPath) {
report.warn(
`Failed to detect the entry point for the generated files. Make sure you have a valid ${kleur.blue(
'source'
)} field in your ${kleur.blue('package.json')}.`
);
}
report.error(
`The ${kleur.blue(name)} field in ${kleur.blue(
'package.json'
)} points to a non-existent file: ${kleur.blue(
value
)}.\nVerify the path points to the correct file under ${kleur.blue(
path.relative(root, output)
)}${
generatedEntryPath
? ` (found ${kleur.blue(generatedEntryPath)}).`
: '.'
}`
);
throw new Error(`Found incorrect path in '${name}' field.`);
}
throw e;
}
})
);
} else {
const generatedEntryPath = await getGeneratedEntryPath();
report.warn(
`No ${fields
.map((field) => kleur.blue(field.name))
.join(' or ')} field found in ${kleur.blue('package.json')}. Consider ${
generatedEntryPath
? `pointing to ${kleur.blue(generatedEntryPath)}`
: `adding ${fields.length > 1 ? 'them' : 'it'}`
} so that consumers of your package can import your package.`
);
}
}