/
babel.js
709 lines (631 loc) Β· 22.7 KB
/
babel.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
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
// @flow
import assert from 'assert';
import path from 'path';
import {
bundle,
bundler,
distDir,
getNextBuild,
inputFS as fs,
outputFS,
removeDistDirectory,
run,
sleep,
} from '@parcel/test-utils';
import Logger from '@parcel/logger';
import os from 'os';
import {spawnSync} from 'child_process';
import tempy from 'tempy';
import {md} from '@parcel/diagnostic';
const parcelCli = require.resolve('parcel/src/bin.js');
const inputDir = path.join(__dirname, '/input');
describe('babel', function () {
let subscription;
beforeEach(async function () {
// TODO maybe don't do this for all tests
await sleep(100);
await outputFS.rimraf(inputDir);
await sleep(100);
});
afterEach(async () => {
await removeDistDirectory();
if (subscription) {
await subscription.unsubscribe();
subscription = null;
}
});
it.skip('should auto install @babel/core v7', async function () {
let originalPkg = await fs.readFile(
__dirname + '/integration/babel-7-autoinstall/package.json',
);
let b = await bundle(
__dirname + '/integration/babel-7-autoinstall/index.js',
);
let output = await run(b);
assert.equal(typeof output, 'object');
assert.equal(typeof output.default, 'function');
assert.equal(output.default(), 3);
let pkg = await fs.readFile(
__dirname + '/integration/babel-7-autoinstall/package.json',
);
assert(JSON.parse(pkg).devDependencies['@babel/core']);
await fs.writeFile(
__dirname + '/integration/babel-7-autoinstall/package.json',
originalPkg,
);
});
it.skip('should auto install babel plugins', async function () {
let originalPkg = await fs.readFile(
__dirname + '/integration/babel-plugin-autoinstall/package.json',
);
let b = await bundle(
__dirname + '/integration/babel-plugin-autoinstall/index.js',
);
let output = await run(b);
assert.equal(typeof output, 'object');
assert.equal(typeof output.default, 'function');
assert.equal(output.default(), 3);
let pkg = await fs.readFile(
__dirname + '/integration/babel-plugin-autoinstall/package.json',
);
assert(JSON.parse(pkg).devDependencies['@babel/core']);
assert(
JSON.parse(pkg).devDependencies[
'@babel/plugin-proposal-class-properties'
],
);
await fs.writeFile(
__dirname + '/integration/babel-plugin-autoinstall/package.json',
originalPkg,
);
});
it('should support compiling with babel using .babelrc config', async function () {
await bundle(path.join(__dirname, '/integration/babelrc-custom/index.js'));
let file = await outputFS.readFile(path.join(distDir, 'index.js'), 'utf8');
assert(!file.includes('REPLACE_ME'));
assert(file.includes('hello there'));
});
it('should support compiling with babel using babel.config.json config without warnings', async function () {
let messages = [];
let loggerDisposable = Logger.onLog(message => {
messages.push(message);
});
await bundle(
path.join(__dirname, '/integration/babel-config-json-custom/index.js'),
{
logLevel: 'verbose',
},
);
loggerDisposable.dispose();
let file = await outputFS.readFile(path.join(distDir, 'index.js'), 'utf8');
assert(!file.includes('REPLACE_ME'));
assert(file.includes('hello there'));
assert.deepEqual(messages, []);
});
it.skip('should support compiling with babel using browserslist for different environments', async function () {
async function testBrowserListMultipleEnv(projectBasePath) {
// Transpiled destructuring, like r = p.prop1, o = p.prop2, a = p.prop3;
const prodRegExp =
/\S+ ?= ?\S+\.prop1,\s*?\S+ ?= ?\S+\.prop2,\s*?\S+ ?= ?\S+\.prop3;/;
// ES6 Destructuring, like in the source;
const devRegExp =
/const ?{\s*prop1(:.+)?,\s*prop2(:.+)?,\s*prop3(:.+)?\s*} ?= ?.*/;
let file;
// Dev build test
await bundle(path.join(__dirname, projectBasePath, '/index.js'));
file = await outputFS.readFile(path.join(distDir, 'index.js'), 'utf8');
assert.equal(devRegExp.test(file), true);
assert.equal(prodRegExp.test(file), false);
// Prod build test
await bundle(path.join(__dirname, projectBasePath, '/index.js'), {
defaultTargetOptions: {
shouldOptimize: false,
},
});
file = await outputFS.readFile(path.join(distDir, 'index.js'), 'utf8');
assert.equal(prodRegExp.test(file), true);
assert.equal(devRegExp.test(file), false);
}
await testBrowserListMultipleEnv(
'/integration/babel-browserslist-multiple-env',
);
await testBrowserListMultipleEnv(
'/integration/babel-browserslist-multiple-env-as-string',
);
});
it.skip('should compile node_modules with browserslist to app target', async function () {
await bundle(
path.join(
__dirname,
'/integration/babel-node-modules-browserslist/index.js',
),
);
let file = await outputFS.readFile(path.join(distDir, 'index.js'), 'utf8');
assert(file.includes('function Foo'));
assert(file.includes('function Bar'));
});
it('should strip away flow types', async function () {
let b = await bundle(
path.join(__dirname, '/integration/babel-strip-flow-types/index.js'),
);
let output = await run(b);
assert.equal(typeof output, 'function');
assert.equal(output(), 'hello world');
let file = await outputFS.readFile(path.join(distDir, 'index.js'), 'utf8');
assert(!file.includes('OptionsType'));
});
it('should support compiling with babel using babel.config.js config', async function () {
await bundle(
path.join(__dirname, '/integration/babel-config-js/src/index.js'),
);
let file = await outputFS.readFile(path.join(distDir, 'index.js'), 'utf8');
assert(!file.includes('REPLACE_ME'));
assert(file.match(/return \d+;/));
});
it('should support compiling with babel using babel.config.js config with a require in it', async function () {
await bundle(
path.join(__dirname, '/integration/babel-config-js-require/src/index.js'),
);
let file = await outputFS.readFile(path.join(distDir, 'index.js'), 'utf8');
assert(!file.includes('REPLACE_ME'));
assert(file.match(/return \d+;/));
});
it('should support multitarget builds using a custom babel config with @parcel/babel-preset-env', async function () {
let fixtureDir = path.join(
__dirname,
'/integration/babel-config-js-multitarget',
);
await bundle(path.join(fixtureDir, 'src/index.js'));
let [modern, legacy] = await Promise.all([
outputFS.readFile(path.join(fixtureDir, 'dist/modern/index.js'), 'utf8'),
outputFS.readFile(path.join(fixtureDir, 'dist/legacy/index.js'), 'utf8'),
]);
assert(modern.includes('class Foo'));
assert(modern.includes('this.x ** 2'));
assert(!legacy.includes('class Foo'));
assert(!legacy.includes('this.x ** 2'));
await outputFS.rimraf(path.join(fixtureDir, 'dist'));
});
it('should support multitarget builds using a custom babel config with @parcel/babel-plugin-transform-runtime', async function () {
let fixtureDir = path.join(
__dirname,
'/integration/babel-config-js-multitarget-transform-runtime',
);
await bundle(path.join(fixtureDir, 'src/index.js'), {
mode: 'production',
defaultTargetOptions: {
shouldOptimize: false,
},
});
let [main, esmodule] = await Promise.all([
outputFS.readFile(path.join(fixtureDir, 'dist/main.js'), 'utf8'),
outputFS.readFile(path.join(fixtureDir, 'dist/module.js'), 'utf8'),
]);
assert(main.includes('"@babel/runtime/helpers/objectSpread2"'));
assert(esmodule.includes('"@babel/runtime/helpers/esm/objectSpread2"'));
await outputFS.rimraf(path.join(fixtureDir, 'dist'));
});
it('should support building with custom babel config when running parcel globally', async function () {
let tmpDir = tempy.directory();
let distDir = path.join(tmpDir, 'dist');
await fs.ncp(
path.join(__dirname, '/integration/babelrc-custom'),
path.join(tmpDir, '/input'),
);
await bundle(path.join(tmpDir, '/input/index.js'), {
targets: {
modern: {
engines: {
node: '^4.0.0',
},
distDir,
},
},
shouldAutoInstall: true,
});
let file = await outputFS.readFile(path.join(distDir, 'index.js'), 'utf8');
assert(!file.includes('REPLACE_ME'));
assert(file.includes('hello there'));
});
it('should support merging .babelrc and babel.config.json in a monorepo', async function () {
await bundle(
path.join(
__dirname,
'/integration/babel-config-monorepo/packages/pkg-a/src/index.js',
),
);
let file = await outputFS.readFile(path.join(distDir, 'index.js'), 'utf8');
assert(!file.includes('REPLACE_ME'));
assert(file.includes('string from a plugin in babel.config.json'));
assert(!file.includes('ANOTHER_THING_TO_REPLACE'));
assert(file.includes('string from a plugin in .babelrc'));
assert(file.includes('SOMETHING ELSE'));
assert(!file.includes('string from a plugin from a different sub-package'));
});
describe('Babel envName', () => {
it('should prefer BABEL_ENV to NODE_ENV', async () => {
await bundle(
path.join(__dirname, '/integration/babel-env-name/index.js'),
{
targets: {main: {distDir, engines: {browsers: ['ie 11']}}},
env: {BABEL_ENV: 'production', NODE_ENV: 'development'},
},
);
let file = await outputFS.readFile(
path.join(distDir, 'index.js'),
'utf8',
);
assert(!file.includes('class Foo'));
});
it('should invalidate when BABEL_ENV changes', async () => {
await bundle(
path.join(__dirname, '/integration/babel-env-name/index.js'),
{
targets: {main: {distDir, engines: {}}},
shouldDisableCache: false,
},
);
let file = await outputFS.readFile(
path.join(distDir, 'index.js'),
'utf8',
);
assert(file.includes('class Foo'));
await bundle(
path.join(__dirname, '/integration/babel-env-name/index.js'),
{shouldDisableCache: false, env: {BABEL_ENV: 'production'}},
);
file = await outputFS.readFile(path.join(distDir, 'index.js'), 'utf8');
assert(!file.includes('class Foo'));
});
it('should invalidate when NODE_ENV changes from BABEL_ENV', async () => {
await bundle(
path.join(__dirname, '/integration/babel-env-name/index.js'),
{
targets: {main: {distDir, engines: {}}},
shouldDisableCache: false,
env: {NODE_ENV: 'production'},
},
);
let file = await outputFS.readFile(
path.join(distDir, 'index.js'),
'utf8',
);
assert(!file.includes('class Foo'));
await bundle(
path.join(__dirname, '/integration/babel-env-name/index.js'),
{
targets: {main: {distDir, engines: {}}},
shouldDisableCache: false,
env: {BABEL_ENV: 'development'},
},
);
file = await outputFS.readFile(path.join(distDir, 'index.js'), 'utf8');
assert(file.includes('class Foo'));
});
it('should be "production" if Parcel is run in production mode', async () => {
await bundle(
path.join(__dirname, '/integration/babel-env-name/index.js'),
{
targets: {main: {distDir, engines: {browsers: ['ie 11']}}},
mode: 'production',
},
);
let file = await outputFS.readFile(
path.join(distDir, 'index.js'),
'utf8',
);
assert(!file.includes('class Foo'));
});
});
describe('tests needing the real filesystem', () => {
afterEach(async () => {
try {
await fs.rimraf(inputDir);
await fs.rimraf(distDir);
} catch (e) {
if (e.code === 'ENOENT') {
throw e;
}
}
});
it('should rebuild when .babelrc changes', async function () {
let inputDir = tempy.directory();
let differentPath = path.join(inputDir, 'differentConfig');
let configPath = path.join(inputDir, '.babelrc');
await fs.ncp(
path.join(__dirname, 'integration/babelrc-custom'),
inputDir,
);
let b = bundler(path.join(inputDir, 'index.js'), {
outputFS: fs,
shouldAutoInstall: true,
});
subscription = await b.watch();
await getNextBuild(b);
let distFile = await fs.readFile(path.join(distDir, 'index.js'), 'utf8');
assert(distFile.includes('hello there'));
await fs.copyFile(differentPath, configPath);
await new Promise(resolve => setTimeout(resolve, 100));
// On Windows only, `fs.utimes` arguments must be instances of `Date`,
// otherwise it fails. For Mac instances on Azure CI, using a Date instance
// does not update the utime correctly, so for all other platforms, use a
// number.
// https://github.com/nodejs/node/issues/5561
let now = os.platform() === 'win32' ? new Date() : Date.now();
// fs.copyFile does not reliably update mtime, which babel uses to invalidate cached file contents
await fs.utimes(configPath, now, now);
await getNextBuild(b);
distFile = await fs.readFile(path.join(distDir, 'index.js'), 'utf8');
assert(!distFile.includes('hello there'));
assert(distFile.includes('something different'));
});
it('should invalidate babel.config.js across runs', async function () {
let dateRe = /return (\d+);/;
let fixtureDir = path.join(__dirname, '/integration/babel-config-js');
let distDir = path.resolve(fixtureDir, './dist');
let cacheDir = path.resolve(fixtureDir, '.parcel-cache');
await fs.rimraf(distDir);
await fs.rimraf(cacheDir);
await fs.rimraf(path.resolve(fixtureDir, './node_modules/.cache'));
let build = () =>
spawnSync(
'node',
[
parcelCli,
'build',
'src/index.js',
'--no-optimize',
'--no-scope-hoist',
],
{
cwd: fixtureDir,
env: {
...process.env,
PARCEL_WORKERS: '0',
},
},
);
build();
let file = await fs.readFile(path.join(distDir, 'index.js'), 'utf8');
assert(!file.includes('REPLACE_ME'));
let firstMatch = file.match(dateRe);
assert(firstMatch != null);
let firstDatestamp = firstMatch[1];
build();
file = await fs.readFile(path.join(distDir, 'index.js'), 'utf8');
let secondMatch = file.match(dateRe);
assert(secondMatch != null);
let secondDatestamp = secondMatch[1];
assert.notEqual(firstDatestamp, secondDatestamp);
});
it('should invalidate when babel plugins are upgraded across runs', async function () {
let fixtureDir = path.join(
__dirname,
'/integration/babel-plugin-upgrade',
);
await fs.ncp(path.join(fixtureDir), inputDir);
await fs.rimraf(path.join(__dirname, '.parcel-cache'));
let build = () =>
spawnSync(
'node',
[parcelCli, 'build', 'index.js', '--no-optimize', '--no-scope-hoist'],
{
cwd: inputDir,
env: {
...process.env,
PARCEL_WORKERS: '0',
},
},
);
build();
let file = await fs.readFile(
path.join(inputDir, 'dist', 'index.js'),
'utf8',
);
assert(!file.includes('REPLACE_ME'));
assert(file.includes('hello there'));
await fs.writeFile(
path.join(inputDir, 'node_modules/babel-plugin-dummy/message.js'),
'module.exports = "something different"',
);
await fs.writeFile(
path.join(inputDir, 'node_modules/babel-plugin-dummy/package.json'),
JSON.stringify({name: 'babel-plugin-dummy', version: '1.1.0'}),
);
await fs.writeFile(
path.join(inputDir, 'yarn.lock'),
'# yarn.lock has been updated',
);
build();
file = await fs.readFile(path.join(inputDir, 'dist', 'index.js'), 'utf8');
assert(!file.includes('REPLACE_ME'));
assert(!file.includes('hello there'));
assert(file.includes('something different'));
});
});
it('should enable shippedProposals with @parcel/babel-preset-env in custom babelrc', async function () {
let b = await bundle(
path.join(
__dirname,
'/integration/babel-preset-env-shippedProposals/index.js',
),
);
let file = await outputFS.readFile(b.getBundles()[0].filePath, 'utf8');
assert(!file.includes('#priv'));
let output = await run(b);
assert.strictEqual(typeof output, 'object');
assert.strictEqual(output.default, 123);
});
it('should compile with custom babel plugin plus default transforms', async function () {
let b = await bundle(
path.join(__dirname, '/integration/babel-custom/index.js'),
);
let file = await outputFS.readFile(b.getBundles()[0].filePath, 'utf8');
assert(!file.includes('class Test'));
assert(!file.includes('REPLACE_ME'));
assert(!file.includes('#private'));
let output = await run(b);
assert.strictEqual(typeof output, 'object');
assert.strictEqual(output.default, 'hello');
});
it('should compile with custom babel plugin and jsx', async function () {
let b = await bundle(
path.join(__dirname, '/integration/babel-custom/jsx.js'),
);
let file = await outputFS.readFile(b.getBundles()[0].filePath, 'utf8');
assert(!file.includes('REPLACE_ME'));
assert(file.includes('React.createElement'));
});
it('should compile with custom babel plugin and typescript', async function () {
let b = await bundle(
path.join(__dirname, '/integration/babel-custom/ts.ts'),
);
let file = await outputFS.readFile(b.getBundles()[0].filePath, 'utf8');
assert(!file.includes('class Test'));
assert(!file.includes('REPLACE_ME'));
assert(!file.includes('#private'));
assert(!file.includes('interface'));
let output = await run(b);
assert.strictEqual(typeof output, 'object');
assert.strictEqual(output.default, 'hello');
});
it('should compile with custom babel plugin and tsx', async function () {
let b = await bundle(
path.join(__dirname, '/integration/babel-custom/tsx.tsx'),
);
let file = await outputFS.readFile(b.getBundles()[0].filePath, 'utf8');
assert(!file.includes('REPLACE_ME'));
assert(!file.includes('interface'));
assert(file.includes('React.createElement'));
});
it('should warn when a babel config contains only redundant plugins', async function () {
let messages = [];
let loggerDisposable = Logger.onLog(message => {
messages.push(message);
});
let filePath = path.join(__dirname, '/integration/babel-warn-all/index.js');
await bundle(filePath);
loggerDisposable.dispose();
let babelrcPath = path.resolve(path.dirname(filePath), '.babelrc');
assert.deepEqual(messages, [
{
type: 'log',
level: 'warn',
diagnostics: [
{
origin: '@parcel/transformer-babel',
message: md`Parcel includes transpilation by default. Babel config __${path.relative(
process.cwd(),
babelrcPath,
)}__ contains only redundant presets. Deleting it may significantly improve build performance.`,
codeFrames: [
{
filePath: babelrcPath,
codeHighlights: [
{
message: undefined,
start: {
line: 2,
column: 15,
},
end: {
line: 2,
column: 33,
},
},
],
},
],
hints: [
md`Delete __${path.relative(process.cwd(), babelrcPath)}__`,
],
documentationURL:
'https://parceljs.org/languages/javascript/#default-presets',
},
{
origin: '@parcel/transformer-babel',
message:
"@babel/preset-env does not support Parcel's targets, which will likely result in unnecessary transpilation and larger bundle sizes.",
codeFrames: [
{
filePath: path.resolve(path.dirname(filePath), '.babelrc'),
codeHighlights: [
{
message: undefined,
start: {
line: 2,
column: 15,
},
end: {
line: 2,
column: 33,
},
},
],
},
],
hints: [
"Either remove __@babel/preset-env__ to use Parcel's builtin transpilation, or replace with __@parcel/babel-preset-env__",
],
documentationURL:
'https://parceljs.org/languages/javascript/#custom-plugins',
},
],
},
]);
});
it('should warn when a babel config contains redundant plugins', async function () {
let messages = [];
let loggerDisposable = Logger.onLog(message => {
messages.push(message);
});
let filePath = path.join(
__dirname,
'/integration/babel-warn-some/index.js',
);
await bundle(filePath);
loggerDisposable.dispose();
let babelrcPath = path.resolve(path.dirname(filePath), '.babelrc');
assert.deepEqual(messages, [
{
type: 'log',
level: 'warn',
diagnostics: [
{
origin: '@parcel/transformer-babel',
message: md`Parcel includes transpilation by default. Babel config __${path.relative(
process.cwd(),
babelrcPath,
)}__ includes the following redundant presets: __@parcel/babel-preset-env__. Removing these may improve build performance.`,
codeFrames: [
{
filePath: babelrcPath,
codeHighlights: [
{
message: undefined,
start: {
line: 2,
column: 15,
},
end: {
line: 2,
column: 40,
},
},
],
},
],
hints: [
md`Remove the above presets from __${path.relative(
process.cwd(),
babelrcPath,
)}__`,
],
documentationURL:
'https://parceljs.org/languages/javascript/#default-presets',
},
],
},
]);
});
});