-
-
Notifications
You must be signed in to change notification settings - Fork 601
/
Copy pathtest.mjs
1334 lines (1174 loc) · 39.3 KB
/
test.mjs
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
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* eslint-disable line-comment-position, no-new-func, no-undefined */
import { createRequire } from 'module';
import * as os from 'os';
import * as path from 'path';
import { fileURLToPath } from 'url';
import { nodeResolve } from '@rollup/plugin-node-resolve';
import test from 'ava';
import { getLocator } from 'locate-character';
import { rollup } from 'rollup';
import { install } from 'source-map-support';
import {
commonjs,
executeBundle,
getCodeFromBundle,
normalizePathSlashes
} from './helpers/util.mjs';
const require = createRequire(import.meta.url);
const { peerDependencies } = require('../package.json');
const { testBundle } = require('../../../util/test.js');
install();
test.beforeEach(() => process.chdir(fileURLToPath(new URL('.', import.meta.url))));
const loader = (modules) => {
return {
load(id) {
if (Object.hasOwnProperty.call(modules, id)) {
return modules[id];
}
return null;
},
resolveId(id) {
if (Object.hasOwnProperty.call(modules, id)) {
return id;
}
return null;
}
};
};
test('Rollup peer dependency has correct format', (t) => {
t.regex(peerDependencies.rollup, /^\^\d+\.\d+\.\d+(\|\|\^\d+\.\d+\.\d+)*$/);
});
test('exposes plugin version', (t) => {
const plugin = commonjs();
t.regex(plugin.version, /^\d+\.\d+\.\d+/);
});
// most of these should be moved over to function...
test('generates a sourcemap', async (t) => {
const bundle = await rollup({
input: 'fixtures/samples/sourcemap/main.js',
plugins: [commonjs({ sourceMap: true })]
});
const {
output: [{ code, map }]
} = await bundle.generate({
exports: 'auto',
format: 'cjs',
sourcemap: true,
sourcemapFile: path.resolve('bundle.js')
});
// source-map uses the presence of fetch to detect browser environments which
// breaks in Node 18
const { fetch } = global;
delete global.fetch;
const { SourceMapConsumer } = await import('source-map');
const smc = await new SourceMapConsumer(map);
global.fetch = fetch;
const locator = getLocator(code, { offsetLine: 1 });
let generatedLoc = locator('42');
let loc = smc.originalPositionFor(generatedLoc); // 42
t.is(loc.source, 'fixtures/samples/sourcemap/foo.js');
t.is(loc.line, 1);
t.is(loc.column, 15);
generatedLoc = locator('log');
loc = smc.originalPositionFor(generatedLoc); // log
t.is(loc.source, 'fixtures/samples/sourcemap/main.js');
t.is(loc.line, 3);
t.is(loc.column, 8);
});
test('supports an array of multiple entry points', async (t) => {
const bundle = await rollup({
input: [
'fixtures/samples/multiple-entry-points/b.js',
'fixtures/samples/multiple-entry-points/c.js'
],
plugins: [commonjs()]
});
const { output } = await bundle.generate({
exports: 'auto',
format: 'cjs',
chunkFileNames: '[name].js'
});
if (Array.isArray(output)) {
t.is(output.length, 3);
t.truthy(output.find(({ fileName }) => fileName === 'b.js'));
t.truthy(output.find(({ fileName }) => fileName === 'c.js'));
} else {
t.is(Object.keys(output).length, 3);
t.is('b.js' in output, true);
t.is('c.js' in output, true);
}
});
test('supports an object of multiple entry points', async (t) => {
const bundle = await rollup({
input: {
b: require.resolve('./fixtures/samples/multiple-entry-points/b.js'),
c: require.resolve('./fixtures/samples/multiple-entry-points/c.js')
},
plugins: [nodeResolve(), commonjs()]
});
const { output } = await bundle.generate({
exports: 'auto',
format: 'cjs',
chunkFileNames: '[name].js'
});
if (Array.isArray(output)) {
t.is(output.length, 3);
t.truthy(output.find(({ fileName }) => fileName === 'b.js'));
t.truthy(output.find(({ fileName }) => fileName === 'c.js'));
} else {
t.is(Object.keys(output).length, 3);
t.is('b.js' in output, true);
t.is('c.js' in output, true);
}
});
test('handles references to `global`', async (t) => {
const bundle = await rollup({
input: 'fixtures/samples/global/main.js',
plugins: [commonjs()]
});
const code = await getCodeFromBundle(bundle);
const mockWindow = {};
const mockGlobal = {};
const mockSelf = {};
const fn = new Function('module', 'globalThis', 'window', 'global', 'self', code);
fn({}, undefined, mockWindow, mockGlobal, mockSelf);
t.is(mockWindow.foo, 'bar', code);
t.is(mockGlobal.foo, undefined, code);
t.is(mockSelf.foo, undefined, code);
fn({}, undefined, undefined, mockGlobal, mockSelf);
t.is(mockGlobal.foo, 'bar', code);
t.is(mockSelf.foo, undefined, code);
fn({}, undefined, undefined, undefined, mockSelf);
t.is(mockSelf.foo, 'bar', code);
});
test('handles multiple references to `global`', async (t) => {
const bundle = await rollup({
input: 'fixtures/samples/global-in-if-block/main.js',
plugins: [commonjs()]
});
const code = await getCodeFromBundle(bundle);
const fn = new Function('module', 'exports', 'globalThis', code);
const module = { exports: {} };
const globalThis = {};
fn(module, module.exports, globalThis);
t.is(globalThis.count, 1);
fn(module, module.exports, globalThis);
t.is(globalThis.count, 2);
});
test('handles transpiled CommonJS modules', async (t) => {
const bundle = await rollup({
input: 'fixtures/samples/corejs/literal-with-default.js',
plugins: [commonjs()]
});
const code = await getCodeFromBundle(bundle);
const module = { exports: {} };
const fn = new Function('module', 'exports', code);
fn(module, module.exports);
t.is(module.exports, 'foobar', code);
});
test('handles successive builds', async (t) => {
const plugin = commonjs();
let bundle = await rollup({
input: 'fixtures/samples/corejs/literal-with-default.js',
plugins: [plugin]
});
await bundle.generate({
exports: 'auto',
format: 'cjs'
});
bundle = await rollup({
input: 'fixtures/samples/corejs/literal-with-default.js',
plugins: [plugin]
});
const code = await getCodeFromBundle(bundle);
const module = { exports: {} };
const fn = new Function('module', 'exports', code);
fn(module, module.exports);
t.is(module.exports, 'foobar', code);
});
test.serial('handles symlinked node_modules with preserveSymlinks: false', (t) => {
const cwd = process.cwd();
// ensure we resolve starting from a directory with
// symlinks in node_modules.
process.chdir(fileURLToPath(new URL('fixtures/samples/symlinked-node-modules', import.meta.url)));
return t.notThrowsAsync(
rollup({
input: './index.js',
onwarn(warning) {
// should not get a warning about unknown export 'foo'
throw new Error(`Unexpected warning: ${warning.message}`);
},
plugins: [
nodeResolve({
preserveSymlinks: false,
preferBuiltins: false
}),
commonjs()
]
})
.then((v) => {
process.chdir(cwd);
return v;
})
.catch((err) => {
process.chdir(cwd);
throw err;
})
);
});
test('converts a CommonJS module with custom file extension', async (t) => {
const bundle = await rollup({
input: 'fixtures/samples/extension/main.coffee',
plugins: [commonjs({ extensions: ['.coffee'] })]
});
t.is((await executeBundle(bundle, t)).exports, 42);
});
test('import CommonJS module with esm property should get default export ', async (t) => {
const bundle = await rollup({
input: 'fixtures/samples/cjs-with-esm-property/main.js',
plugins: [
commonjs({
defaultIsModuleExports: 'auto'
})
]
});
const result = await executeBundle(bundle, t);
t.is(result.error, undefined);
const bundle2 = await rollup({
input: 'fixtures/samples/cjs-with-esm-property/main.js',
plugins: [
commonjs({
defaultIsModuleExports: true
})
]
});
const result2 = await executeBundle(bundle2, t);
t.is(result2.error.message, 'libExports is not a function');
});
test('identifies named exports from object literals', async (t) => {
const bundle = await rollup({
input: 'fixtures/samples/named-exports-from-object-literal/main.js',
plugins: [commonjs()]
});
t.plan(3);
await testBundle(t, bundle);
});
test('can ignore references to `global`', async (t) => {
const bundle = await rollup({
input: 'fixtures/samples/ignore-global/main.js',
plugins: [commonjs({ ignoreGlobal: true })],
onwarn: (warning) => {
if (warning.code === 'THIS_IS_UNDEFINED') return;
// eslint-disable-next-line no-console
console.warn(warning.message);
}
});
const code = await getCodeFromBundle(bundle);
const { exports, global } = await executeBundle(bundle, t);
t.is(exports.immediate1, global.setImmediate, code);
t.is(exports.immediate2, global.setImmediate, code);
t.is(exports.immediate3, null, code);
});
test('can handle parens around right have node while producing default export', async (t) => {
const bundle = await rollup({
input: 'fixtures/samples/paren-expression/index.js',
plugins: [commonjs()]
});
t.is((await executeBundle(bundle, t, { testEntry: 'index.js' })).exports, 42);
});
test('typeof transforms: correct-scoping', async (t) => {
const bundle = await rollup({
input: 'fixtures/samples/umd/correct-scoping.js',
plugins: [commonjs()]
});
t.is((await executeBundle(bundle, t, { testEntry: 'correct-scoping.js' })).exports, 'object');
});
test('typeof transforms: protobuf', async (t) => {
const bundle = await rollup({
input: 'fixtures/samples/umd/protobuf.js',
external: ['bytebuffer', 'foo'],
plugins: [commonjs()]
});
t.is((await executeBundle(bundle, t, { testEntry: 'protobuf.js' })).exports, true);
});
test('typeof transforms: sinon', async (t) => {
const bundle = await rollup({
input: 'fixtures/samples/umd/sinon.js',
plugins: [commonjs()]
});
const {
output: [{ code }]
} = await bundle.generate({ format: 'es' });
t.is(code.indexOf('typeof require'), -1, code);
t.is(code.indexOf('typeof module'), -1, code);
t.is(code.indexOf('typeof define'), -1, code);
});
test('deconflicts helper name', async (t) => {
const bundle = await rollup({
input: 'fixtures/samples/deconflict-helpers/main.js',
plugins: [commonjs()]
});
const { exports } = await executeBundle(bundle, t);
t.not(exports, 'nope');
});
test('deconflicts reserved keywords', async (t) => {
const bundle = await rollup({
input: 'fixtures/samples/reserved-as-property/main.js',
plugins: [commonjs()]
});
const reservedProp = (await executeBundle(bundle, t, { exports: 'default' })).exports.delete;
t.is(reservedProp, 'foo');
});
test('does not process the entry file when it has a leading "." (issue #63)', async (t) => {
const bundle = await rollup({
input: './fixtures/function/basic/main.js',
plugins: [commonjs()]
});
await t.notThrowsAsync(executeBundle(bundle, t));
});
test('respects other plugins', async (t) => {
const bundle = await rollup({
input: 'fixtures/samples/other-transforms/main.js',
plugins: [
{
transform(code, id) {
if (id[0] === '\0') return null;
return code.replace('40', '41');
}
},
commonjs()
]
});
await t.notThrowsAsync(executeBundle(bundle, t));
});
test('rewrites top-level defines', async (t) => {
const bundle = await rollup({
input: 'fixtures/samples/define-is-undefined/main.js',
plugins: [commonjs()]
});
function define() {
throw new Error('nope');
}
define.amd = true;
const { exports } = await executeBundle(bundle, t, { context: { define } });
t.is(exports, 42);
});
test('respects options.external', async (t) => {
const bundle = await rollup({
input: 'fixtures/samples/external/main.js',
plugins: [nodeResolve(), commonjs()],
external: ['baz']
});
const code = await getCodeFromBundle(bundle);
t.is(code.indexOf('hello'), -1);
const { exports } = await executeBundle(bundle, t);
t.is(exports, 'HELLO');
});
test('prefers to set name using directory for index files', async (t) => {
const bundle = await rollup({
input: 'fixtures/samples/rename-index/main.js',
plugins: [commonjs()]
});
const code = await getCodeFromBundle(bundle);
t.is(code.indexOf('var index'), -1, 'does not contain index');
t.not(code.indexOf('var invalidVar'), -1, 'contains invalidVar');
t.not(code.indexOf('var validVar'), -1, 'contains validVar');
t.not(code.indexOf('var nonIndex'), -1, 'contains nonIndex');
});
test('correctly wraps the default export from a CommonJS module when it is a class', async (t) => {
const bundle = await rollup({
input: 'fixtures/samples/es-module-with-class-as-default-export/main.js',
plugins: [commonjs()]
});
const result = await executeBundle(bundle, t);
t.is(result.error, undefined);
});
test('does not warn even if the ES module does not export "default"', async (t) => {
const warns = [];
await rollup({
input: 'fixtures/samples/es-modules-without-default-export/main.js',
plugins: [commonjs()],
onwarn: (warn) => warns.push(warn)
});
t.is(warns.length, 0);
await rollup({
input: 'fixtures/function/bare-import/bar.js',
plugins: [commonjs()],
onwarn: (warn) => warns.push(warn)
});
t.is(warns.length, 0);
await rollup({
input: 'fixtures/function/bare-import-comment/main.js',
plugins: [commonjs()],
onwarn: (warn) => warns.push(warn)
});
t.is(warns.length, 0);
});
test('compiles with cache', async (t) => {
const plugin = commonjs();
const { cache } = await rollup({
input: 'fixtures/function/index/main.js',
plugins: [plugin]
});
await t.notThrowsAsync(
rollup({
input: 'fixtures/function/index/main.js',
plugins: [plugin],
cache
})
);
});
test('creates an error with a code frame when parsing fails', async (t) => {
try {
await rollup({
input: 'fixtures/samples/invalid-syntax/main.js',
plugins: [commonjs()]
});
} catch (error) {
t.is(
error.frame,
`1: /* eslint-disable */
2: export const foo = 2,
^`
);
}
});
// Virtual modules are treated as "requireReturnsDefault: 'always'" to avoid interop
test('ignores virtual modules', async (t) => {
const bundle = await rollup({
input: 'fixtures/samples/ignore-virtual-modules/main.js',
plugins: [
commonjs(),
{
resolveId(id) {
if (id === '\0virtual' || id === '\0resolved-virtual') {
return '\0resolved-virtual';
}
return null;
},
load(id) {
if (id === '\0resolved-virtual') {
return 'export default "Virtual export"';
}
return null;
}
}
]
});
t.is((await executeBundle(bundle, t)).exports, 'Virtual export');
});
test('does not produce warnings when importing .mjs without default export', async (t) => {
const bundle = await rollup({
input: 'main.mjs',
onwarn(warning) {
// The interop should not trigger a "default is not exported" warning
throw new Error(`Unexpected warning: ${warning.message}`);
},
plugins: [
commonjs(),
{
load(id) {
if (id === 'main.mjs') {
return 'import cjs from "cjs.js"; export default cjs;';
}
if (id === 'cjs.js') {
// CJS libraries expect to receive a CJS file here
return 'module.exports = require("fromNodeModules");';
}
if (id === 'fromNodeModules.mjs') {
return 'export const result = "from esm";';
}
return null;
},
resolveId(id) {
// rollup-plugin-node-resolve usually prefers ESM versions
if (id === 'fromNodeModules') {
return 'fromNodeModules.mjs';
}
return id;
}
}
]
});
t.deepEqual((await executeBundle(bundle, t)).exports, { result: 'from esm' });
});
test('produces optimized code when importing esm with a known default export', async (t) => {
const bundle = await rollup({
input: 'main.js',
plugins: [
commonjs({ requireReturnsDefault: true }),
loader({
'main.js': 'module.exports = require("esm.js")',
'esm.js': 'export const ignored = "ignored"; export default "default"'
})
]
});
t.snapshot(await getCodeFromBundle(bundle));
});
test('produces optimized code when importing esm without a default export', async (t) => {
const bundle = await rollup({
input: 'main.js',
plugins: [
commonjs(),
loader({
'main.js': 'module.exports = require("esm.js")',
'esm.js': 'export const value = "value";'
})
]
});
t.snapshot(await getCodeFromBundle(bundle));
});
test('handles array destructuring assignment', async (t) => {
const bundle = await rollup({
input: 'fixtures/samples/array-destructuring-assignment/main.js',
plugins: [commonjs({ sourceMap: true })]
});
t.snapshot(await getCodeFromBundle(bundle, { exports: 'named' }));
});
test('can spread an object into module.exports', async (t) => {
const bundle = await rollup({
input: 'fixtures/samples/module-exports-spread/main.js',
plugins: [commonjs()]
});
t.snapshot(await getCodeFromBundle(bundle));
});
test('logs a warning when the deprecated namedExports option is used', async (t) => {
let message;
const bundle = await rollup({
onwarn(warning) {
({ message } = warning);
},
input: 'fixtures/samples/sourcemap/main.js',
plugins: [commonjs({ namedExports: { foo: ['bar'] } })]
});
await getCodeFromBundle(bundle);
t.is(
message,
'The namedExports option from "@rollup/plugin-commonjs" is deprecated. Named exports are now handled automatically.'
);
});
// This test uses worker threads to simulate an empty internal cache and needs at least Node 12
if (Number(/^v(\d+)/.exec(process.version)[1]) >= 12) {
test('can be cached across instances', async (t) => {
const bundle = await rollup({
input: 'fixtures/samples/caching/main.js',
plugins: [commonjs()]
});
const { cache } = bundle;
const code = await getCodeFromBundle(bundle);
// We do a second run in a worker so that all internal state is cleared
const { Worker } = await import('worker_threads');
const getRollupUpCodeWithCache = new Worker(
fileURLToPath(new URL('fixtures/samples/caching/rollupWorker.js', import.meta.url)),
{
workerData: cache
}
);
t.is(code, await new Promise((done) => getRollupUpCodeWithCache.on('message', done)));
});
}
test('does not affect subsequently created instances when called with `requireReturnsDefault: "preferred"`', async (t) => {
const input = 'fixtures/function/import-esm-require-returns-default-preferred/main.js';
const options = { requireReturnsDefault: 'preferred' };
const instance1 = commonjs(options);
const bundle1 = await rollup({
input,
plugins: [instance1]
});
const code1 = (await bundle1.generate({})).output[0].code;
const instance2 = commonjs(options);
const bundle2 = await rollup({
input,
plugins: [instance2]
});
const code2 = (await bundle2.generate({})).output[0].code;
t.is(code1, code2);
});
// This test works only on Windows, which treats both forward and backward
// slashes as path separators
if (os.platform() === 'win32') {
test('supports both forward and backward slash as path separator in directory-based modules', async (t) => {
const bundle = await rollup({
input: 'fixtures/samples/module-path-separator/main.js',
plugins: [
// Ad-hoc plugin that reverses the path separator of foo/index.js
{
name: 'test-path-separator-reverser',
async resolveId(source, importer) {
if (source.endsWith('foo')) {
const fullPath = path.resolve(path.dirname(importer), source, 'index.js');
// Ensure that the module ID uses a non-default path separator
return fullPath.replace(/[\\/]/g, (sep) => (sep === '/' ? '\\' : '/'));
}
return null;
}
},
commonjs()
]
});
const code = await getCodeFromBundle(bundle);
t.regex(code, /var foo(\$\d+)? = {}/);
});
}
test('throws when there is a dynamic require from outside dynamicRequireRoot', async (t) => {
let error = null;
try {
await rollup({
input: 'fixtures/samples/dynamic-require-outside-root/main.js',
plugins: [
commonjs({
dynamicRequireRoot: 'fixtures/samples/dynamic-require-outside-root/nested',
dynamicRequireTargets: ['fixtures/samples/dynamic-require-outside-root/nested/target.js']
})
]
});
} catch (err) {
error = err;
}
const cwd = process.cwd();
const id = normalizePathSlashes(
path.join(cwd, 'fixtures/samples/dynamic-require-outside-root/main.js')
);
const dynamicRequireRoot = normalizePathSlashes(
path.join(cwd, 'fixtures/samples/dynamic-require-outside-root/nested')
);
const minimalDynamicRequireRoot = normalizePathSlashes(
path.join(cwd, 'fixtures/samples/dynamic-require-outside-root')
);
t.like(error, {
message: `"${id}" contains dynamic require statements but it is not within the current dynamicRequireRoot "${dynamicRequireRoot}". You should set dynamicRequireRoot to "${minimalDynamicRequireRoot}" or one of its parent directories.`,
pluginCode: 'DYNAMIC_REQUIRE_OUTSIDE_ROOT',
normalizedId: id,
normalizedDynamicRequireRoot: dynamicRequireRoot
});
});
test('does not throw when a dynamic require uses different slashes than dynamicRequireRoot', async (t) => {
let error = null;
try {
await rollup({
input: 'fixtures/samples/dynamic-require-outside-root/main.js',
plugins: [
commonjs({
dynamicRequireRoot: 'fixtures\\samples\\dynamic-require-outside-root',
dynamicRequireTargets: [
'fixtures\\samples\\dynamic-require-outside-root\\nested\\target.js'
]
})
]
});
} catch (err) {
error = err;
}
t.is(error, null);
});
// On Windows, avoid a false error about a module not being in the dynamic require root due to
// incoherent slashes/backslashes in the paths.
if (os.platform() === 'win32') {
test('correctly asserts dynamicRequireRoot on Windows', async (t) => {
let error = null;
try {
await rollup({
input: 'fixtures/samples/dynamic-require-outside-root/main.js',
plugins: [
commonjs({
dynamicRequireRoot: 'fixtures/samples/dynamic-require-outside-root',
dynamicRequireTargets: [
'fixtures/samples/dynamic-require-outside-root/nested/target.js'
]
})
]
});
} catch (err) {
error = err;
}
t.is(error, null);
});
}
test('does not transform typeof exports for mixed modules', async (t) => {
const bundle = await rollup({
input: 'fixtures/samples/mixed-module-typeof-exports/main.js',
plugins: [commonjs({ transformMixedEsModules: true })]
});
const {
output: [{ code }]
} = await bundle.generate({ format: 'es' });
t.is(code.includes('typeof exports'), true, '"typeof exports" not found in the code');
t.snapshot(code);
});
test('throws when using an old node_resolve version', async (t) => {
let error = null;
try {
await rollup({
input: 'ignored',
plugins: [commonjs(), { name: nodeResolve().name }]
});
} catch (err) {
error = err;
}
t.like(error, {
message:
'Insufficient @rollup/plugin-node-resolve version: "@rollup/plugin-commonjs" requires at least @rollup/[email protected].'
});
});
test('throws when using an inadequate node_resolve version', async (t) => {
let error = null;
try {
await rollup({
input: 'ignored',
plugins: [commonjs(), { name: nodeResolve().name, version: '13.0.5' }]
});
} catch (err) {
error = err;
}
t.like(error, {
message:
'Insufficient @rollup/plugin-node-resolve version: "@rollup/plugin-commonjs" requires at least @rollup/[email protected] but found @rollup/[email protected].'
});
});
const onwarn = (warning) => {
if (warning.code !== 'CIRCULAR_DEPENDENCY') {
throw new Error(warning.message);
}
};
const getTransformTracker = (trackedId) => {
const trackedTransforms = [];
const meta = {};
return {
meta,
trackedTransforms,
tracker: {
name: 'transform-tracker',
transform(code, id) {
trackedTransforms.push(id);
},
moduleParsed({ id, meta: { commonjs: commonjsMeta } }) {
if (id === trackedId) {
Object.assign(meta, commonjsMeta);
}
}
}
};
};
test('handles when an imported dependency of an ES module changes type', async (t) => {
const { meta, tracker, trackedTransforms } = getTransformTracker('dep.js');
const modules = {};
const resetModules = () => {
modules['main.js'] = "import {dep} from 'dep.js';export default dep;";
modules['dep.js'] = "export const dep = 'esm';";
};
const options = {
input: 'main.js',
plugins: [commonjs(), loader(modules), tracker],
onwarn
};
resetModules();
let bundle = await rollup(options);
t.is(meta.isCommonJS, false);
t.deepEqual((await executeBundle(bundle, t)).exports, 'esm');
t.deepEqual(trackedTransforms, ['main.js', 'dep.js']);
trackedTransforms.length = 0;
const esCode = await getCodeFromBundle(bundle);
t.snapshot(esCode);
modules['dep.js'] = "exports.dep = 'cjs';";
options.cache = bundle.cache;
bundle = await rollup(options);
t.is(meta.isCommonJS, 'withRequireFunction');
t.deepEqual((await executeBundle(bundle, t)).exports, 'cjs');
t.deepEqual(trackedTransforms, [
'dep.js',
'main.js',
'\0dep.js?commonjs-es-import',
'\0commonjsHelpers.js',
'\0dep.js?commonjs-exports'
]);
trackedTransforms.length = 0;
const cjsCode = await getCodeFromBundle(bundle);
t.snapshot(cjsCode);
modules['dep.js'] = "exports.dep = 'cjs'; exports.dep += require('dep.js').dep;";
options.cache = bundle.cache;
bundle = await rollup(options);
t.is(meta.isCommonJS, 'withRequireFunction');
t.deepEqual((await executeBundle(bundle, t)).exports, 'cjscjs');
t.deepEqual(trackedTransforms, ['dep.js']);
trackedTransforms.length = 0;
const wrappedCode = await getCodeFromBundle(bundle);
t.snapshot(wrappedCode);
resetModules();
options.cache = bundle.cache;
bundle = await rollup(options);
t.is(meta.isCommonJS, false);
t.deepEqual((await executeBundle(bundle, t)).exports, 'esm');
t.deepEqual(trackedTransforms, ['dep.js', 'main.js']);
trackedTransforms.length = 0;
t.is(await getCodeFromBundle(bundle), esCode);
modules['dep.js'] = "exports.dep = 'cjs'; exports.dep += require('dep.js').dep;";
options.cache = bundle.cache;
bundle = await rollup(options);
t.is(meta.isCommonJS, 'withRequireFunction');
t.deepEqual((await executeBundle(bundle, t)).exports, 'cjscjs');
t.deepEqual(trackedTransforms, [
'dep.js',
'main.js',
'\0dep.js?commonjs-es-import',
'\0commonjsHelpers.js',
'\0dep.js?commonjs-exports'
]);
trackedTransforms.length = 0;
t.is(await getCodeFromBundle(bundle), wrappedCode);
modules['dep.js'] = "exports.dep = 'cjs';";
options.cache = bundle.cache;
bundle = await rollup(options);
t.is(meta.isCommonJS, 'withRequireFunction');
t.deepEqual((await executeBundle(bundle, t)).exports, 'cjs');
t.deepEqual(trackedTransforms, ['dep.js']);
trackedTransforms.length = 0;
t.is(await getCodeFromBundle(bundle), cjsCode);
resetModules();
options.cache = bundle.cache;
bundle = await rollup(options);
t.is(meta.isCommonJS, false);
t.deepEqual((await executeBundle(bundle, t)).exports, 'esm');
t.deepEqual(trackedTransforms, ['dep.js', 'main.js']);
trackedTransforms.length = 0;
t.is(await getCodeFromBundle(bundle), esCode);
});
test('handles when a dynamically imported dependency of an ES module changes type', async (t) => {
const { meta, tracker, trackedTransforms } = getTransformTracker('dep.js');
const modules = {};
const resetModules = () => {
modules['main.js'] = "export default import('dep.js').then(({dep}) => dep);";
modules['dep.js'] = "export const dep = 'esm';";
};
const options = {
input: 'main.js',
plugins: [commonjs(), loader(modules), tracker],
onwarn
};
resetModules();
let bundle = await rollup(options);
t.is(meta.isCommonJS, false);
t.deepEqual(await (await executeBundle(bundle, t)).exports, 'esm');
t.deepEqual(trackedTransforms, ['main.js', 'dep.js']);
trackedTransforms.length = 0;
modules['dep.js'] = "exports.dep = 'cjs';";
options.cache = bundle.cache;
bundle = await rollup(options);
t.is(meta.isCommonJS, 'withRequireFunction');
t.deepEqual(await (await executeBundle(bundle, t)).exports, 'cjs');
t.deepEqual(trackedTransforms, [
'dep.js',
'main.js',
'\0dep.js?commonjs-es-import',
'\0commonjsHelpers.js',
'\0dep.js?commonjs-exports'
]);
trackedTransforms.length = 0;
modules['dep.js'] = "exports.dep = 'cjs'; exports.dep += require('dep.js').dep;";
options.cache = bundle.cache;
bundle = await rollup(options);
t.is(meta.isCommonJS, 'withRequireFunction');
t.deepEqual(await (await executeBundle(bundle, t)).exports, 'cjscjs');