-
-
Notifications
You must be signed in to change notification settings - Fork 5.6k
/
index.js
434 lines (390 loc) 路 12.1 KB
/
index.js
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
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
//@flow
import { SemVer, lt } from "semver";
import { logPlugin } from "./debug";
import getOptionSpecificExcludesFor from "./get-option-specific-excludes";
import { removeUnnecessaryItems } from "./filter-items";
import moduleTransformations from "./module-transformations";
import normalizeOptions from "./normalize-options";
import { proposalPlugins, pluginSyntaxMap } from "../data/shipped-proposals";
import {
plugins as pluginsList,
pluginsBugfixes as pluginsBugfixesList,
} from "./plugins-compat-data";
import overlappingPlugins from "@babel/compat-data/overlapping-plugins";
import removeRegeneratorEntryPlugin from "./polyfills/regenerator";
import legacyBabelPolyfillPlugin from "./polyfills/babel-polyfill";
import _pluginCoreJS2 from "babel-plugin-polyfill-corejs2";
import _pluginCoreJS3 from "babel-plugin-polyfill-corejs3";
import _pluginRegenerator from "babel-plugin-polyfill-regenerator";
const pluginCoreJS2 = _pluginCoreJS2.default;
const pluginCoreJS3 = _pluginCoreJS3.default;
const pluginRegenerator = _pluginRegenerator.default;
import getTargets, {
prettifyTargets,
filterItems,
isRequired,
type Targets,
type InputTargets,
} from "@babel/helper-compilation-targets";
import availablePlugins from "./available-plugins";
import { declare } from "@babel/helper-plugin-utils";
import typeof ModuleTransformationsType from "./module-transformations";
import type { BuiltInsOption, ModuleOption } from "./types";
// TODO: Remove in Babel 8
export function isPluginRequired(targets: Targets, support: Targets) {
return isRequired("fake-name", targets, {
compatData: { "fake-name": support },
});
}
function filterStageFromList(
list: { [feature: string]: Targets },
stageList: Set<string>,
) {
return Object.keys(list).reduce((result, item) => {
if (!stageList.has(item)) {
result[item] = list[item];
}
return result;
}, {});
}
const pluginLists = {
withProposals: {
withoutBugfixes: pluginsList,
withBugfixes: Object.assign({}, pluginsList, pluginsBugfixesList),
},
withoutProposals: {
withoutBugfixes: filterStageFromList(pluginsList, proposalPlugins),
withBugfixes: filterStageFromList(
Object.assign({}, pluginsList, pluginsBugfixesList),
proposalPlugins,
),
},
};
function getPluginList(proposals: boolean, bugfixes: boolean) {
if (proposals) {
if (bugfixes) return pluginLists.withProposals.withBugfixes;
else return pluginLists.withProposals.withoutBugfixes;
} else {
if (bugfixes) return pluginLists.withoutProposals.withBugfixes;
else return pluginLists.withoutProposals.withoutBugfixes;
}
}
const getPlugin = (pluginName: string) => {
const plugin = availablePlugins[pluginName]();
if (!plugin) {
throw new Error(
`Could not find plugin "${pluginName}". Ensure there is an entry in ./available-plugins.js for it.`,
);
}
return plugin;
};
export const transformIncludesAndExcludes = (opts: Array<string>): Object => {
return opts.reduce(
(result, opt) => {
const target = opt.match(/^(es|es6|es7|esnext|web)\./)
? "builtIns"
: "plugins";
result[target].add(opt);
return result;
},
{
all: opts,
plugins: new Set(),
builtIns: new Set(),
},
);
};
export const getModulesPluginNames = ({
modules,
transformations,
shouldTransformESM,
shouldTransformDynamicImport,
shouldTransformExportNamespaceFrom,
shouldParseTopLevelAwait,
}: {|
modules: ModuleOption,
transformations: ModuleTransformationsType,
shouldTransformESM: boolean,
shouldTransformDynamicImport: boolean,
shouldTransformExportNamespaceFrom: boolean,
shouldParseTopLevelAwait: boolean,
|}) => {
const modulesPluginNames = [];
if (modules !== false && transformations[modules]) {
if (shouldTransformESM) {
modulesPluginNames.push(transformations[modules]);
}
if (
shouldTransformDynamicImport &&
shouldTransformESM &&
modules !== "umd"
) {
modulesPluginNames.push("proposal-dynamic-import");
} else {
if (shouldTransformDynamicImport) {
console.warn(
"Dynamic import can only be supported when transforming ES modules" +
" to AMD, CommonJS or SystemJS. Only the parser plugin will be enabled.",
);
}
modulesPluginNames.push("syntax-dynamic-import");
}
} else {
modulesPluginNames.push("syntax-dynamic-import");
}
if (shouldTransformExportNamespaceFrom) {
modulesPluginNames.push("proposal-export-namespace-from");
} else {
modulesPluginNames.push("syntax-export-namespace-from");
}
if (shouldParseTopLevelAwait) {
modulesPluginNames.push("syntax-top-level-await");
}
return modulesPluginNames;
};
export const getPolyfillPlugins = ({
useBuiltIns,
corejs,
polyfillTargets,
include,
exclude,
proposals,
shippedProposals,
regenerator,
debug,
}: {
useBuiltIns: BuiltInsOption,
corejs: typeof SemVer | null | false,
polyfillTargets: Targets,
include: Set<string>,
exclude: Set<string>,
proposals: boolean,
shippedProposals: boolean,
regenerator: boolean,
debug: boolean,
}) => {
const polyfillPlugins = [];
if (useBuiltIns === "usage" || useBuiltIns === "entry") {
const pluginOptions = {
method: `${useBuiltIns}-global`,
version: corejs ? corejs.toString() : undefined,
targets: polyfillTargets,
include,
exclude,
proposals,
shippedProposals,
debug,
};
if (corejs) {
if (useBuiltIns === "usage") {
if (corejs.major === 2) {
polyfillPlugins.push(
[pluginCoreJS2, pluginOptions],
[legacyBabelPolyfillPlugin, { usage: true }],
);
} else {
polyfillPlugins.push(
[pluginCoreJS3, pluginOptions],
[legacyBabelPolyfillPlugin, { usage: true, deprecated: true }],
);
}
if (regenerator) {
polyfillPlugins.push([
pluginRegenerator,
{ method: "usage-global", debug },
]);
}
} else {
if (corejs.major === 2) {
polyfillPlugins.push(
[legacyBabelPolyfillPlugin, { regenerator }],
[pluginCoreJS2, pluginOptions],
);
} else {
polyfillPlugins.push(
[pluginCoreJS3, pluginOptions],
[legacyBabelPolyfillPlugin, { deprecated: true }],
);
if (!regenerator) {
polyfillPlugins.push([removeRegeneratorEntryPlugin, pluginOptions]);
}
}
}
}
}
return polyfillPlugins;
};
function getLocalTargets(
optionsTargets,
ignoreBrowserslistConfig,
configPath,
browserslistEnv,
) {
if (optionsTargets?.esmodules && optionsTargets.browsers) {
console.warn(`
@babel/preset-env: esmodules and browsers targets have been specified together.
\`browsers\` target, \`${optionsTargets.browsers.toString()}\` will be ignored.
`);
}
return getTargets(
// $FlowIgnore optionsTargets doesn't have an "uglify" property anymore
(optionsTargets: InputTargets),
{ ignoreBrowserslistConfig, configPath, browserslistEnv },
);
}
function supportsStaticESM(caller) {
return !!caller?.supportsStaticESM;
}
function supportsDynamicImport(caller) {
return !!caller?.supportsDynamicImport;
}
function supportsExportNamespaceFrom(caller) {
return !!caller?.supportsExportNamespaceFrom;
}
function supportsTopLevelAwait(caller) {
return !!caller?.supportsTopLevelAwait;
}
export default declare((api, opts) => {
api.assertVersion(7);
const babelTargets = api.targets();
const {
bugfixes,
configPath,
debug,
exclude: optionsExclude,
forceAllTransforms,
ignoreBrowserslistConfig,
include: optionsInclude,
loose,
modules,
shippedProposals,
spec,
targets: optionsTargets,
useBuiltIns,
corejs: { version: corejs, proposals },
browserslistEnv,
} = normalizeOptions(opts);
let targets = babelTargets;
if (
// @babel/core < 7.13.0 doesn't load targets (api.targets() always
// returns {} thanks to @babel/helper-plugin-utils), so we always want
// to fallback to the old targets behavior in this case.
lt(api.version, "7.13.0") ||
// If any browserslist-related option is specified, fallback to the old
// behavior of not using the targets specified in the top-level options.
opts.targets ||
opts.configPath ||
opts.browserslistEnv ||
opts.ignoreBrowserslistConfig
) {
if (!process.env.BABEL_8_BREAKING) {
// eslint-disable-next-line no-var
var hasUglifyTarget = false;
if (optionsTargets?.uglify) {
hasUglifyTarget = true;
delete optionsTargets.uglify;
console.warn(`
The uglify target has been deprecated. Set the top level
option \`forceAllTransforms: true\` instead.
`);
}
}
targets = getLocalTargets(
optionsTargets,
ignoreBrowserslistConfig,
configPath,
browserslistEnv,
);
}
const transformTargets = (
process.env.BABEL_8_BREAKING
? forceAllTransforms
: forceAllTransforms || hasUglifyTarget
)
? {}
: targets;
const include = transformIncludesAndExcludes(optionsInclude);
const exclude = transformIncludesAndExcludes(optionsExclude);
const compatData = getPluginList(shippedProposals, bugfixes);
const shouldSkipExportNamespaceFrom =
(modules === "auto" && api.caller?.(supportsExportNamespaceFrom)) ||
(modules === false &&
!isRequired("proposal-export-namespace-from", transformTargets, {
compatData,
includes: include.plugins,
excludes: exclude.plugins,
}));
const modulesPluginNames = getModulesPluginNames({
modules,
transformations: moduleTransformations,
// TODO: Remove the 'api.caller' check eventually. Just here to prevent
// unnecessary breakage in the short term for users on older betas/RCs.
shouldTransformESM: modules !== "auto" || !api.caller?.(supportsStaticESM),
shouldTransformDynamicImport:
modules !== "auto" || !api.caller?.(supportsDynamicImport),
shouldTransformExportNamespaceFrom: !shouldSkipExportNamespaceFrom,
shouldParseTopLevelAwait: !api.caller || api.caller(supportsTopLevelAwait),
});
const pluginNames = filterItems(
compatData,
include.plugins,
exclude.plugins,
transformTargets,
modulesPluginNames,
getOptionSpecificExcludesFor({ loose }),
pluginSyntaxMap,
);
removeUnnecessaryItems(pluginNames, overlappingPlugins);
const polyfillPlugins = getPolyfillPlugins({
useBuiltIns,
corejs,
polyfillTargets: targets,
include: include.builtIns,
exclude: exclude.builtIns,
proposals,
shippedProposals,
regenerator: pluginNames.has("transform-regenerator"),
debug,
});
const pluginUseBuiltIns = useBuiltIns !== false;
const plugins = Array.from(pluginNames)
.map(pluginName => {
if (
pluginName === "proposal-class-properties" ||
pluginName === "proposal-private-methods" ||
// This is not included in preset-env yet, but let's keep it here so we
// don't forget about it in the future.
pluginName === "proposal-private-property-in-object"
) {
return [
getPlugin(pluginName),
{
loose: loose
? "#__internal__@babel/preset-env__prefer-true-but-false-is-ok-if-it-prevents-an-error"
: "#__internal__@babel/preset-env__prefer-false-but-true-is-ok-if-it-prevents-an-error",
},
];
}
return [
getPlugin(pluginName),
{ spec, loose, useBuiltIns: pluginUseBuiltIns },
];
})
.concat(polyfillPlugins);
if (debug) {
console.log("@babel/preset-env: `DEBUG` option");
console.log("\nUsing targets:");
console.log(JSON.stringify(prettifyTargets(targets), null, 2));
console.log(`\nUsing modules transform: ${modules.toString()}`);
console.log("\nUsing plugins:");
pluginNames.forEach(pluginName => {
logPlugin(pluginName, targets, compatData);
});
if (!useBuiltIns) {
console.log(
"\nUsing polyfills: No polyfills were added, since the `useBuiltIns` option was not set.",
);
}
}
return { plugins };
});