forked from rollup/plugins
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathas-input-plugin.mjs
More file actions
602 lines (526 loc) · 17 KB
/
as-input-plugin.mjs
File metadata and controls
602 lines (526 loc) · 17 KB
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
import { createRequire } from 'node:module';
import * as nodePath from 'node:path';
import * as fs from 'node:fs';
import { fileURLToPath } from 'url';
import test from 'ava';
import { rollup } from 'rollup';
import jsonPlugin from '@rollup/plugin-json';
import nodeResolvePlugin from '@rollup/plugin-node-resolve';
import { createFilter } from '@rollup/pluginutils';
import babelPlugin, { getBabelOutputPlugin, createBabelInputPluginFactory } from 'current-package';
import { getCode } from '../../../util/test.js';
const DIRNAME = fileURLToPath(new URL('.', import.meta.url));
const FIXTURES = `${DIRNAME}/fixtures/`;
function getLocation(source, charIndex) {
const lines = source.split('\n');
const len = lines.length;
let lineStart = 0;
for (let i = 0; i < len; i += 1) {
const line = lines[i];
// +1 for newline
const lineEnd = lineStart + line.length + 1;
if (lineEnd > charIndex) {
return { line: i + 1, column: charIndex - lineStart };
}
lineStart = lineEnd;
}
throw new Error('Could not determine location of character');
}
function replaceConsoleLogProperty({ types: t }) {
return {
name: 'replace-console-log-property',
visitor: {
MemberExpression(path, state) {
const { opts } = state;
if (path.node.property.name === 'log') {
path.get('property').replaceWith(t.identifier(opts.replace));
}
}
}
};
}
async function generate(input, babelOptions = {}, generateOptions = {}, rollupOptions = {}) {
const bundle = await rollup({
input: FIXTURES + input,
plugins: [babelPlugin({ babelHelpers: 'bundled', ...babelOptions })],
...rollupOptions
});
return getCode(bundle, {
format: 'cjs',
exports: 'auto',
...generateOptions
});
}
test('runs code through babel', async (t) => {
const code = await generate('basic/main.js');
t.false(code.includes('const'));
t.is(
code,
`'use strict';
var answer = 42;
console.log("the answer is ".concat(answer));
`
);
});
test('adds helpers', async (t) => {
const code = await generate('class/main.js');
t.true(code.includes('function _classCallCheck'));
});
test('adds helpers in loose mode', async (t) => {
const code = await generate('class-loose/main.js');
t.true(code.includes('function _inherits'));
});
test('does not babelify excluded code', async (t) => {
const code = await generate('exclusions/main.js', { exclude: '**/foo.js' });
// eslint-disable-next-line no-template-curly-in-string
t.false(code.includes('${foo()}'));
t.true(code.includes('=> 42'));
t.is(
code,
`'use strict';
const foo = () => 42;
console.log("the answer is ".concat(foo()));
`
);
});
test('does not babelify excluded code with custom filter', async (t) => {
const filter = createFilter([], '**/foo.js');
const code = await generate('exclusions/main.js', { filter });
// eslint-disable-next-line no-template-curly-in-string
t.false(code.includes('${foo()}'));
t.true(code.includes('=> 42'));
t.is(
code,
`'use strict';
const foo = () => 42;
console.log("the answer is ".concat(foo()));
`
);
});
test('does not babelify excluded code with code-based filter', async (t) => {
const filter = (id, code) => code.includes('the answer is');
const code = await generate('exclusions/main.js', { filter });
// eslint-disable-next-line no-template-curly-in-string
t.false(code.includes('${foo()}'));
t.true(code.includes('=> 42'));
t.is(
code,
`'use strict';
const foo = () => 42;
console.log("the answer is ".concat(foo()));
`
);
});
test('does babelify included code with custom filter', async (t) => {
const filter = createFilter('**/foo.js', [], {
resolve: DIRNAME
});
const code = await generate('exclusions/main.js', { filter });
// eslint-disable-next-line no-template-curly-in-string
t.true(code.includes('${foo()}'));
t.false(code.includes('=> 42'));
t.is(
code,
`'use strict';
var foo = function foo() {
return 42;
};
console.log(\`the answer is \${foo()}\`);
`
);
});
test('does babelify excluded code with code-based filter', async (t) => {
const filter = (id, code) => !code.includes('the answer is');
const code = await generate('exclusions/main.js', { filter });
// eslint-disable-next-line no-template-curly-in-string
t.true(code.includes('${foo()}'));
t.false(code.includes('=> 42'));
t.is(
code,
`'use strict';
var foo = function foo() {
return 42;
};
console.log(\`the answer is \${foo()}\`);
`
);
});
test('can not pass include or exclude when custom filter specified', async (t) => {
const filter = createFilter('**/foo.js', [], {
resolve: DIRNAME
});
let errorWithExclude = '';
try {
await generate('exclusions/main.js', { filter, exclude: [] });
} catch (e) {
errorWithExclude = e.message;
}
t.true(!!errorWithExclude);
let errorWithInclude = '';
try {
await generate('exclusions/main.js', { filter, include: [] });
} catch (e) {
errorWithInclude = e.message;
}
t.true(!!errorWithInclude);
});
test('generates sourcemap by default', async (t) => {
const bundle = await rollup({
input: `${FIXTURES}class/main.js`,
plugins: [babelPlugin({ babelHelpers: 'bundled' })]
});
const {
output: [{ code, map }]
} = await bundle.generate({ format: 'cjs', exports: 'auto', sourcemap: true });
const target = 'log';
// 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 loc = getLocation(code, code.indexOf(target));
const original = smc.originalPositionFor(loc);
t.deepEqual(original, {
source: 'test/fixtures/class/main.js'.split(nodePath.sep).join('/'),
line: 3,
column: 12,
name: target
});
});
test('works with proposal-decorators (rollup/rollup-plugin-babel#18)', async (t) => {
await t.notThrowsAsync(() =>
rollup({
input: `${FIXTURES}proposal-decorators/main.js`,
plugins: [babelPlugin({ babelHelpers: 'bundled' })]
})
);
});
test('checks config per-file', async (t) => {
const code = await generate('checks/main.js', {}, { format: 'es' });
t.true(code.includes('class Foo'));
t.true(code.includes('var Bar'));
t.false(code.includes('class Bar'));
});
test('allows transform-runtime to be used instead of bundled helpers', async (t) => {
const warnings = [];
const code = await generate(
'runtime-helpers/main.js',
{ babelHelpers: 'runtime' },
{},
{
onwarn(warning) {
warnings.push(warning.message);
}
}
);
t.deepEqual(warnings, [
`"@babel/runtime/helpers/createClass" is imported by "test/fixtures/runtime-helpers/main.js", but could not be resolved – treating it as an external dependency.`,
`"@babel/runtime/helpers/classCallCheck" is imported by "test/fixtures/runtime-helpers/main.js", but could not be resolved – treating it as an external dependency.`
]);
t.is(
code,
`'use strict';
var _createClass = require('@babel/runtime/helpers/createClass');
var _classCallCheck = require('@babel/runtime/helpers/classCallCheck');
var Foo = /*#__PURE__*/_createClass(function Foo() {
_classCallCheck(this, Foo);
});
module.exports = Foo;
`
);
});
test('allows transform-runtime to inject esm version of helpers', async (t) => {
const warnings = [];
const code = await generate(
'runtime-helpers-esm/main.js',
{ babelHelpers: 'runtime' },
{
format: 'es'
},
{
onwarn(warning) {
warnings.push(warning.message);
}
}
);
t.deepEqual(warnings, [
`"@babel/runtime/helpers/esm/createClass" is imported by "test/fixtures/runtime-helpers-esm/main.js", but could not be resolved – treating it as an external dependency.`,
`"@babel/runtime/helpers/esm/classCallCheck" is imported by "test/fixtures/runtime-helpers-esm/main.js", but could not be resolved – treating it as an external dependency.`
]);
t.is(
code,
`import _createClass from '@babel/runtime/helpers/esm/createClass';
import _classCallCheck from '@babel/runtime/helpers/esm/classCallCheck';
var Foo = /*#__PURE__*/_createClass(function Foo() {
_classCallCheck(this, Foo);
});
export { Foo as default };
`
);
});
test('allows transform-runtime to be used instead of bundled helpers, but throws when CommonJS is used', async (t) => {
await t.throwsAsync(
() => generate('runtime-helpers-commonjs/main.js', { babelHelpers: 'runtime' }),
{
message: /Rollup requires that your Babel configuration keeps ES6 module syntax intact/
}
);
});
test('allows using external-helpers plugin in combination with @babel/plugin-external-helpers', async (t) => {
const code = await generate('external-helpers/main.js', {
babelHelpers: 'external'
});
t.false(code.includes('function _classCallCheck'));
t.true(code.includes('babelHelpers.classCallCheck'));
t.is(
code,
`'use strict';
var Foo = /*#__PURE__*/babelHelpers.createClass(function Foo() {
babelHelpers.classCallCheck(this, Foo);
});
var Bar = /*#__PURE__*/babelHelpers.createClass(function Bar() {
babelHelpers.classCallCheck(this, Bar);
});
var main = [new Foo(), new Bar()];
module.exports = main;
`
);
});
test('correctly renames helpers (rollup/rollup-plugin-babel#22)', async (t) => {
const code = await generate('named-function-helper/main.js');
t.false(code.includes('babelHelpers_get get'), 'helper was incorrectly renamed');
});
test('runs preflight check correctly in absence of class transformer (rollup/rollup-plugin-babel#23)', async (t) => {
await t.notThrowsAsync(() =>
rollup({
input: `${FIXTURES}no-class-transformer/main.js`,
plugins: [babelPlugin({ babelHelpers: 'bundled' })]
})
);
});
test('produces valid code with typeof helper', async (t) => {
const code = await generate('typeof/main.js');
t.false(code.includes('var typeof'));
});
test('handles babelrc with ignore option used', async (t) => {
const code = await generate('ignored-file/main.js');
t.true(code.includes('class Ignored'));
});
test('transpiles only files with default extensions', async (t) => {
const code = await generate(
'extensions-default/main.js',
{},
{},
{
plugins: [babelPlugin({ babelHelpers: 'bundled' }), jsonPlugin()]
}
);
t.false(code.includes('class Es '), 'should transpile .es');
t.false(code.includes('class Es6 '), 'should transpile .es6');
t.false(code.includes('class Js '), 'should transpile .js');
t.false(code.includes('class Jsx '), 'should transpile .jsx');
t.false(code.includes('class Mjs '), 'should transpile .mjs');
t.true(code.includes('class Other '), 'should not transpile .other');
});
test('transpiles only files with whitelisted extensions', async (t) => {
const code = await generate('extensions-custom/main.js', {
extensions: ['.js', '.other']
});
t.true(code.includes('class Es '), 'should not transpile .es');
t.true(code.includes('class Es6 '), 'should not transpile .es6');
t.false(code.includes('class Js '), 'should transpile .js');
t.true(code.includes('class Jsx '), 'should not transpile .jsx');
t.true(code.includes('class Mjs '), 'should not transpile .mjs');
t.false(code.includes('class Other '), 'should transpile .other');
});
test('transpiles files when path contains query and hash', async (t) => {
const code = await generate(
'with-query-and-hash/main.js',
{},
{},
{
plugins: [
babelPlugin({ babelHelpers: 'bundled' }),
// node-resolve plugin know how to resolve relative request with query
nodeResolvePlugin(),
{
load(id) {
// rollup don't know how to load module with query
// we could teach rollup to discard query while loading module
const [bareId] = id.split(`?`);
return fs.readFileSync(bareId, 'utf-8');
}
}
]
}
);
t.true(code.includes('function WithQuery()'), 'should transpile when path contains query');
t.true(code.includes('function WithHash()'), 'should transpile when path contains hash');
t.true(
code.includes('function WithQueryAndHash()'),
'should transpile when path contains query and hash'
);
});
test('throws when trying to add babel helper unavailable in used @babel/core version', async (t) => {
await t.throwsAsync(
() =>
generate('basic/main.js', {
plugins: [
function testPlugin() {
return {
visitor: {
Program(path, state) {
state.file.addHelper('__nonexistentHelper');
}
}
};
}
]
}),
{
message: `${nodePath.resolve(
DIRNAME,
'fixtures',
'basic',
'main.js'
)}: Unknown helper __nonexistentHelper`
}
);
});
test('works with minified bundled helpers', async (t) => {
const BASE_CHAR_CODE = 'a'.charCodeAt(0);
let counter = 0;
await t.notThrowsAsync(() =>
generate('class/main.js', {
plugins: [
function testPlugin({ types }) {
return {
visitor: {
FunctionDeclaration(path) {
// super simple mangling
path
.get('id')
.replaceWith(types.identifier(String.fromCharCode(BASE_CHAR_CODE + counter)));
counter += 1;
}
}
};
}
]
})
);
});
test('supports customizing the loader', async (t) => {
const expectedRollupContextKeys = ['getCombinedSourcemap', 'getModuleIds', 'emitFile', 'resolve'];
const customBabelPlugin = createBabelInputPluginFactory(() => {
return {
config(cfg) {
t.true(typeof this === 'object', 'override config this context is rollup context');
expectedRollupContextKeys.forEach((key) => {
t.true(
Object.keys(this).includes(key),
`override config this context is rollup context with key ${key}`
);
});
return {
...cfg.options,
plugins: [
...(cfg.options.plugins || []),
// Include a custom plugin in the options.
[replaceConsoleLogProperty, { replace: 'foobaz' }]
]
};
},
result(result) {
t.true(typeof this === 'object', 'override result this context is rollup context');
expectedRollupContextKeys.forEach((key) => {
t.true(
Object.keys(this).includes(key),
`override result this context is rollup context with key ${key}`
);
});
return {
...result,
code: `${result.code}\n// Generated by some custom loader`
};
}
};
});
const bundle = await rollup({
input: `${FIXTURES}basic/main.js`,
plugins: [customBabelPlugin({ babelHelpers: 'bundled' })]
});
const code = await getCode(bundle);
t.true(code.includes('// Generated by some custom loader'), 'adds the custom comment');
t.true(code.includes('console.foobaz'), 'runs the plugin');
});
test('supports overriding the plugin options in custom loader', async (t) => {
const customBabelPlugin = createBabelInputPluginFactory(() => {
return {
options(options) {
// Ignore the js extension to test overriding the options
return { pluginOptions: { ...options, extensions: ['.x'] } };
},
config(cfg) {
return {
...cfg.options,
plugins: [
...(cfg.options.plugins || []),
// Include a custom plugin in the options.
[replaceConsoleLogProperty, { replace: 'foobaz' }]
]
};
},
result(result) {
return {
...result,
code: `${result.code}\n// Generated by some custom loader`
};
}
};
});
const bundle = await rollup({
input: `${FIXTURES}basic/main.js`,
plugins: [customBabelPlugin({ babelHelpers: 'bundled' })]
});
const code = await getCode(bundle);
t.false(
code.includes('// Generated by some custom loader'),
'does not add the comment to ignored file'
);
t.false(code.includes('console.foobaz'), 'does not run the plugin on ignored file');
});
test('uses babel plugins passed in to the rollup plugin', async (t) => {
const code = await generate('basic/main.js', {
plugins: [[replaceConsoleLogProperty, { replace: 'foobaz' }]]
});
t.true(code.includes('console.foobaz'));
});
test('can be used as an input plugin while transforming the output', async (t) => {
const bundle = await rollup({
input: `${FIXTURES}basic/main.js`,
plugins: [
getBabelOutputPlugin({
presets: ['@babel/env']
})
]
});
const code = await getCode(bundle);
t.false(code.includes('const'));
});
test('works as a CJS plugin', async (t) => {
const require = createRequire(import.meta.url);
const babelPluginCjs = require('current-package');
const bundle = await rollup({
input: `${FIXTURES}basic/main.js`,
plugins: [
babelPluginCjs({
presets: ['@babel/env']
})
]
});
const code = await getCode(bundle);
t.false(code.includes('const'));
});